智慧型指標shared ptr

2021-10-09 14:51:22 字數 1453 閱讀 9699

shared_ptr在脫離自己的作用域時候,會自動呼叫析構函式。作用域包含: **塊{}  、被呼叫函式 、main函式等。

#include #include #include #include using namespace std;

class a

~a()

int n;

private:

//int n;

string str;

};void func()

cout<<"execute foo finish"}

cout<<"execute bar finish"shared_ptrsp2(sp1); //sp2也託管 a(2)

cout << "1)" << sp1->n << "," << sp2->n << endl;

//輸出1)2,2

shared_ptrsp3;

a * p = sp1.get(); //p 指向 a(2)

cout << "2)" << p->n << endl;

sp3 = sp1; //sp3也託管 a(2)

cout << "3)" << (*sp3).n << endl; //輸出 2

sp1.reset(); //sp1放棄託管 a(2)

if( !sp1 )

cout << "4)sp1 is null" << endl; //會輸出 a * q = new a(3);

// sp1託管q

//cout << "5)" << sp1->n << endl; //輸出 3 shared_ptrsp4(sp1); //sp4託管a(3)

shared_ptrsp5;

//sp1放棄託管 a(3) cout << "before end main"

std::thread first (foo); // spawn new thread that calls foo()

std::thread second (bar,0); // spawn new thread that calls bar(0)

std::cout << "main, foo and bar now execute concurrently...\n";

// synchronize threads:

first.join(); // pauses until first finishes

second.join(); // pauses until second finishes

std::cout << "foo and bar completed.\n";

return 0; //程式結束,會delete 掉a(2)

}

shared ptr智慧型指標

智慧型指標是乙個行為類似指標的物件。我們在使用堆記憶體時,都需要及時地進行釋放,避免造成記憶體洩漏。但我們偶爾也會忘記將其釋放掉,從而造成記憶體洩漏。並且,在釋放的時候,我們可能對某乙個指標進行了重複釋放,導致程式崩潰的問題。為了能夠解決這些問題,從而有了智慧型指標的設計。智慧型指標一共有四種,分別...

shared ptr(智慧型指標)

只要將 new 運算子返回的指標 p 交給乙個 shared ptr 物件 託管 就不必擔心在 寫delete p語句 實際上根本不需要編寫這條語句,託管 p 的 shared ptr 物件在消亡時會自動執行delete p。而且,該 shared ptr 物件能像指標 p 樣使用,即假設託管 p ...

Boost智慧型指標 shared ptr

boost scoped ptr雖然簡單易用,但它不能共享所有權的特性卻大大限制了其使用範圍,而boost shared ptr可以解決這一侷限。顧名思義,boost shared ptr是可以共享所有權的智慧型指標,首先讓我們通過乙個例子看看它的基本用法 該程式的輸出結果如下 the sample...