-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy path5.2.unique.ptr.cpp
50 lines (39 loc) · 1.14 KB
/
5.2.unique.ptr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// 5.2.unique.ptr.cpp
// chapter 05 start pointers and memory management
// modern c++ tutorial
//
// created by changkun at changkun.de
// https://github.com/changkun/modern-cpp-tutorial
//
#include <iostream>
#include <memory>
struct Foo {
Foo() { std::cout << "Foo::Foo" << std::endl; }
~Foo() { std::cout << "Foo::~Foo" << std::endl; }
void foo() { std::cout << "Foo::foo" << std::endl; }
};
void f(const Foo &) {
std::cout << "f(const Foo&)" << std::endl;
}
int main() {
std::unique_ptr<Foo> p1(std::make_unique<Foo>());
// p1 is not empty, prints
if (p1) p1->foo();
{
std::unique_ptr<Foo> p2(std::move(p1));
// p2 is not empty, prints
f(*p2);
// p2 is not empty, prints
if(p2) p2->foo();
// p1 is empty, no prints
if(p1) p1->foo();
p1 = std::move(p2);
// p2 is empty, no prints
if(p2) p2->foo();
std::cout << "p2 was destroyed" << std::endl;
}
// p1 is not empty, prints
if (p1) p1->foo();
// Foo instance will be destroyed when leaving the scope
}