Skip to content

Commit

Permalink
Merge pull request #21 from kenluobo/add_weak_ptr_test_case
Browse files Browse the repository at this point in the history
Add weak_ptr test case
  • Loading branch information
kenluobo authored Nov 25, 2024
2 parents 8461b13 + 2acaeec commit cdc4654
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions cplusplus/stl/15_weak_ptr.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include "test.h"

//============================================================
template <typename T> struct Node {
std::weak_ptr<Node> next;
T data;

explicit Node(const T &data) : data(data) {}
};

void test_weak_ptr() {
using IntNode = Node<int>;
const auto node1 = std::make_shared<IntNode>(IntNode(1));
const auto node2 = std::make_shared<IntNode>(IntNode(2));
out("node1->data = ", node1->data, "; ",
"node1->use_count = ", node1.use_count());
out("node2->data = ", node2->data, "; ",
"node2->use_count = ", node2.use_count());

out("============================");
node1->next = node2;
node2->next = node1;
out("node1->data = ", node1->data, "; ",
"node1->use_count = ", node1.use_count());
out("node2->data = ", node2->data, "; ",
"node2->use_count = ", node2.use_count());

out("============================");
if (const auto lck = node1->next.lock()) {
out("lck->data = ", lck->data, "; ", "lck->use_count = ", lck.use_count());
out("node1->data = ", node1->data, "; ",
"node1->use_count = ", node1.use_count());
}
out("node1->data = ", node1->data, "; ",
"node1->use_count = ", node1.use_count());
}

//============================================================
void test() {
// todo
TEST(test_weak_ptr);
}

//============================================================
int main() { test(); }

0 comments on commit cdc4654

Please sign in to comment.