C++11 智能指针
https://blog.csdn.net/flowing_wind/article/details/81301001
https://www.cnblogs.com/wuyepeng/p/9741241.html
shared_ptr:
不能用对象指针独立的初始化两个智能指针
例子:
class TestSP{ public: TestSP(string s):str(s) { cout<<"TestSP created\n"; } ~TestSP() { cout<<"TestSP deleted:"<<str<<endl; } const string& getStr() { return str; } void setStr(string s) { str = s; } void print(){ cout<<str<<endl; } private: string str; };
使用:
TestSP *dx = new TestSP("123"); shared_ptr<TestSP> p3(dx); shared_ptr<TestSP> p4(dx);
//或者
shared_ptr<TestSP> p5(p3.get());
这样做,每个智能指针内部计数其实都是1,在p3结束或手动reset后,该对象内存回收了,p4和p5里面的普通指针都变成了悬空指针,然后p4和p5结束时,还是回去对已经回收了的内存调用delete,造成错误(编译不出错,运行会出错)
要用多个指针指向同一块内存,后面的智能指针要用前面的来初始化(通过智能指针类的拷贝构造或赋值运算符):
shared_ptr<TestSP> p6(p3); //这样p3、p6内部计数都是2了
unique_ptr:
unique_ptr不能拷贝、赋值
如果需要把一个unique_ptr的所有权:
例子:
TestSP *dx = new TestSP("123"); unique_ptr<TestSP> up1(dx); unique_ptr<TestSP> up2(new TestSP("456")); up2 = std::move(up1);//up2指向的"456"释放,up2指向"123",up1置为null up1.reset(up2.release());//up2调release,up2置空但"123"没有释放,返回"123"的指针,up1重新绑定到"123" up1.reset();//up1去掉与"123"的绑定,"123"释放,up1置空
weak_ptr:
不控制所指对象生存期
指向shared_ptr管理的对象,不引起shared_ptr引用计数改变,即使还有weak_ptr指向对象,shared_ptr计数为0时还是会释放该对象。
两个shared_ptr相互引用,则计数永远不为0,造成死锁而不释放