adding unique ptr example

This commit is contained in:
Jidong Xiao
2025-04-18 03:39:41 -04:00
committed by JamesFlare1212
parent 284bd60029
commit 0fc129f674
2 changed files with 49 additions and 0 deletions

View File

@@ -380,3 +380,31 @@ int main(){
return 0;
}
```
## 27.16 Exercise
Read the following [program](unique_ptr1.cpp) and answer the questions.
```cpp
#include <iostream>
#include <memory>
int main(){
// Question: is this valid or invalid syntax?
// std::unique_ptr<std::string> s1("test1");
std::unique_ptr<std::string> 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<std::string> 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;
}
```

View File

@@ -0,0 +1,21 @@
#include <iostream>
#include <memory>
int main(){
// Question: is this valid or invalid syntax?
// std::unique_ptr<std::string> s1("test1");
std::unique_ptr<std::string> 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<std::string> 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;
}