一、shared_ptr
main.cpp
#include <iostream>
using namespace std;
int main()
{
shared_ptr<int> myp(new int(100));
shared_ptr<int> myp1(myp);
myp = nullptr;//效果同reset一樣
//myp.reset();
myp1.reset();//置空智能指針,並做減1操作,如果減爲0,則刪除對象
shared_ptr<int> myp2(new int(100));
myp2.reset(new int(200));//原來指向的100對象釋放,重新指向200對象
int *p = myp2.get();//或者int*指針
cout << *myp2 << endl;//解引用
if (myp2)
{
cout << "目前指向對象" << endl;
}
auto p1 = make_shared<int>(100);
auto p2 = make_shared<int>(200);
p1 = p2;//p1原來指向的100對象析構,p1和p2同時指向200對象,strong爲2
int icount = p1.use_count();
if (p1.unique())
{
cout << "只有一個智能指針指向對象" << endl;
}
shared_ptr<int[]> pint(new int[10]);//數組類智能指針定義
}
一個對象可以被多個shared_ptr引用,shared_ptr爲強指針,其引用計數爲0時,所指向的對象釋放。
二、week_ptr
main.cpp
#include <iostream>
using namespace std;
int main()
{
auto p3 = make_shared<int>(100);//strong 1
weak_ptr<int> p4(p3);//strong 1 week 1
//p3.reset();
auto p5 = p4.lock();//如果調用了p3.reset(),強指針引用計數爲0,對象被析構,lock後p5爲nullptr;如果對象還在增加強指針引用計數,strong 2 week 1,返回p5爲強指針
if (p5)
{
cout << "對象並未銷燬" << endl;
}
else
{
cout << "對象已銷燬" << endl;
}
cout << p5.use_count() << endl;//返回弱指針共享對象的其他share_ptr的數量
if (p4.expired())
{
cout << "弱指針指向的對象已銷燬" << endl;
}
p4.reset();//弱指針引用計數減1
}
week_ptr不影響引用計數。
三、unique_ptr
#include <iostream>
using namespace std;
int main()
{
auto p6 = make_unique<int>(100);
unique_ptr<int> p7(new int(200));
//unique_ptr<int> p8(p7);錯誤,unique_ptr不支持拷貝
//unique_ptr<int> p8 = p7;錯誤,unique_ptr不支持賦值運算符
unique_ptr<string> p9(new string("I love china"));
unique_ptr<string> p10 = std::move(p9);//調用的是移動構造函數,移動完後p9爲空,p10指向原來p9所指
if (p9)//fasle
{
cout << "p9指向對象" << endl;
}
if (p10)//true
{
cout << "p10指向對象" << endl;
}
unique_ptr<string> p11(new string("I love china"));
unique_ptr<string> p12(p11.release());//返回裸指針,將該p11智能指針置空
unique_ptr<string> p13(new string("I love china"));
unique_ptr<string> p14(new string("I love china2"));
p13.reset(p14.release());//reset會釋放p13指向對象內存,重新指向p14指向的對象,p14指針置空
unique_ptr<string> p15(new string("I love china"));
p15 = nullptr;//等價於p15.reset()
unique_ptr<string> p16(new string("I love china"));
*p16 = "I love china1";
//unique_ptr<string> p17(p16.get());//錯誤,會讓p16和p17都指向I love china
//shared_ptr包含一個顯示構造函數,用於將unique_ptr右值轉換爲shared_ptr,shared_ptr接管原來的unique_ptr
unique_ptr<string> p18(new string("I love china"));
shared_ptr<string> p19 = std::move(p18);//p18爲空,p19接管對象,strong爲1
}
一個對象只能被一個unique_ptr引用,除非如上所示std::move,release。