0%

unique_ptr函数传参

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
struct A {
A() {cout<<"A::A"<<endl;}
~A() {cout<<"A::~A"<<endl;x=0;}
A(const A& a) : x(a.x) {cout<<"copy ctor"<<endl;}
A(A&& a) noexcept : x(a.x) {cout<<"move ctor"<<endl;}
int x = 1;
};

void f1(unique_ptr<A> &&x) {
cout << x->x<<endl;
x->x = 2;
}

void f2(const unique_ptr<A> &x) {
cout<<x->x<<endl;
x->x = 3;
}

unique_ptr<A> f3(unique_ptr<A> x) {
cout<<x->x<<endl;
return x; // 可以拷贝或赋值一个将要被销毁的unique_ptr (C++ Primer 5th p418)
}

int main() {
auto a = make_unique<A>(); // A::A
f1(move(a)); // 1
f2(a); // 2
a = f3(move(a)); // 3
return 0; // A::~A
}