unique_ptr 表示对某一个对象的唯一一次引用,只要这个unique_ptr 退出生命周期(或者这个unique_ptr 指向其他对象或者调用 reset方法),则被引用的对象自动销毁。
#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;
class A18 {
public:
A18() {
cout << "default constructor" << endl;
}
int say() {
cout << "A say:" << endl;
return 0;
}
~A18() {
cout << "Destructor called" << endl;
}
};
void f0() {
unique_ptr<A18> a(new A18());
a->say();
}
void f1() {
std::unique_ptr<A18> p = std::make_unique<A18>();
p->say();
}
void f2() {
std::unique_ptr<A18> p = std::make_unique<A18>();
//std::unique_ptr<A18> p2 = p;
std::unique_ptr<A18> p2 = std::move(p);
}
std::unique_ptr<A18> f3() {
std::unique_ptr<A18> p = std::make_unique<A18>();
return p;
}
int main() {
f0();
f1();
std::unique_ptr<A18> p3 = f3();
std::unique_ptr<A18> p4 = f3();
sleep(1);
cout << "end" << endl;
return 0;
}
编译: g++ a.cpp -o a
执行: ./a