adding unique ptr example
This commit is contained in:
committed by
JamesFlare1212
parent
284bd60029
commit
0fc129f674
@@ -380,3 +380,31 @@ int main(){
|
|||||||
return 0;
|
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;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
21
lectures/27_garbage_collection/unique_ptr1.cpp
Normal file
21
lectures/27_garbage_collection/unique_ptr1.cpp
Normal 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;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user