From 0fc129f674778287716e47f202363eaa06813a17 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 18 Apr 2025 03:39:41 -0400 Subject: [PATCH] adding unique ptr example --- lectures/27_garbage_collection/README.md | 28 +++++++++++++++++++ .../27_garbage_collection/unique_ptr1.cpp | 21 ++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 lectures/27_garbage_collection/unique_ptr1.cpp diff --git a/lectures/27_garbage_collection/README.md b/lectures/27_garbage_collection/README.md index 7c40b28..dfccb62 100644 --- a/lectures/27_garbage_collection/README.md +++ b/lectures/27_garbage_collection/README.md @@ -380,3 +380,31 @@ int main(){ return 0; } ``` + +## 27.16 Exercise + +Read the following [program](unique_ptr1.cpp) and answer the questions. + +```cpp +#include +#include + +int main(){ + // Question: is this valid or invalid syntax? + // std::unique_ptr s1("test1"); + + std::unique_ptr s1(new std::string("test1")); + + std::cout << *s1 << std::endl; + // Question: can we do this: std::cout << s1.size() << std::endl; + std::cout << s1->size() << std::endl; + + std::unique_ptr s2(std::move(s1)); + + // Question: which of the following line will trigger a seg fault? + // std::cout << "s1:" << *s1 << std::endl; + // std::cout << "s2:" << *s2 << std::endl; + + return 0; +} +``` diff --git a/lectures/27_garbage_collection/unique_ptr1.cpp b/lectures/27_garbage_collection/unique_ptr1.cpp new file mode 100644 index 0000000..0997db7 --- /dev/null +++ b/lectures/27_garbage_collection/unique_ptr1.cpp @@ -0,0 +1,21 @@ +#include +#include + +int main(){ + // Question: is this valid or invalid syntax? + // std::unique_ptr s1("test1"); + + std::unique_ptr s1(new std::string("test1")); + + std::cout << *s1 << std::endl; + // Question: can we do this: std::cout << s1.size() << std::endl; + std::cout << s1->size() << std::endl; + + std::unique_ptr s2(std::move(s1)); + + // Question: which of the following line will trigger a seg fault? + // std::cout << "s1:" << *s1 << std::endl; + // std::cout << "s2:" << *s2 << std::endl; + + return 0; +}