diff --git a/shared_ptr.cpp b/shared_ptr.cpp index 49f7273..5d897fa 100644 --- a/shared_ptr.cpp +++ b/shared_ptr.cpp @@ -1,5 +1,6 @@ #include #include +#include // From Wikipedia. @@ -21,6 +22,24 @@ void shared_ptr() { assert(p1.use_count() == 0); } +void shared_ptr_container() { + std::shared_ptr p1(new int(5)); + std::shared_ptr p2 = p1; // Both now own the memory. + assert(p1.use_count() == 2); + + std::vector> v; + v.push_back(p1); + v.push_back(p1); + assert(p1.use_count() == 4); + p2.reset(); + assert(p1.use_count() == 3); + assert(p2.use_count() == 0); + + v.pop_back(); + v.pop_back(); + assert(p1.use_count() == 1); +} + void weak_ptr() { std::shared_ptr p1(new int(5)); std::weak_ptr wp1 = p1; // p1 owns the memory. @@ -50,5 +69,6 @@ void weak_ptr() { int main() { shared_ptr(); + shared_ptr_container(); weak_ptr(); }