From 329699721facc0e7a1704c486ee2a31df28203e8 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 18 Apr 2025 03:00:08 -0400 Subject: [PATCH] adding shared pointer example --- lectures/27_garbage_collection/README.md | 30 +++++++++++++++++++ .../27_garbage_collection/shared_ptr1.cpp | 23 ++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 lectures/27_garbage_collection/shared_ptr1.cpp diff --git a/lectures/27_garbage_collection/README.md b/lectures/27_garbage_collection/README.md index 76583b2..5401c65 100644 --- a/lectures/27_garbage_collection/README.md +++ b/lectures/27_garbage_collection/README.md @@ -325,3 +325,33 @@ int main() { - std::weak_ptr: Use with shared_ptr. Memory is destroyed when no more shared_ptrs are pointing to object. So each time a weak_ptr is used you should first “lock” the data by creating a shared_ptr. - std::scoped_ptr: (Boost) “Remembers” to delete things when they go out of scope. Alternate to auto_ptr. Cannot be copied. + +## 27.15 Exercise + +In the following program, the use count will be printed 3 times. What exact value will be printed each time? + +```cpp +#include +#include + +int main(){ + std::shared_ptr age(new int(40)); + std::cout << "age is " << *age << std::endl; + + // you can never do this, which is assigning a smarter pointer to a raw pointer. + // int * temp = age; + + { + std::shared_ptr temp = age; + std::cout << "age is " << *temp << std::endl; + std::cout << "the use count is : " << age.use_count() << std::endl; + } + std::cout << "the use count is : " << age.use_count() << std::endl; + + // give up my ownership, it decreases the reference count of the managed object by one. + // if that shared pointer was the last owner (i.e., reference count becomes zero), the object is deleted. + // the shared_ptr itself is now empty (i.e., it holds nullptr). + age.reset(); + std::cout << "the use count is : " << age.use_count() << std::endl; +} +``` diff --git a/lectures/27_garbage_collection/shared_ptr1.cpp b/lectures/27_garbage_collection/shared_ptr1.cpp new file mode 100644 index 0000000..814f14e --- /dev/null +++ b/lectures/27_garbage_collection/shared_ptr1.cpp @@ -0,0 +1,23 @@ +#include +#include + +int main(){ + std::shared_ptr age(new int(40)); + std::cout << "age is " << *age << std::endl; + + // you can never do this, which is assigning a smarter pointer to a raw pointer. + // int * temp = age; + + { + std::shared_ptr temp = age; + std::cout << "age is " << *temp << std::endl; + std::cout << "the use count is : " << age.use_count() << std::endl; + } + std::cout << "the use count is : " << age.use_count() << std::endl; + + // give up my ownership, it decreases the reference count of the managed object by one. + // if that shared pointer was the last owner (i.e., reference count becomes zero), the object is deleted. + // the shared_ptr itself is now empty (i.e., it holds nullptr). + age.reset(); + std::cout << "the use count is : " << age.use_count() << std::endl; +}