代碼1
#include <iostream>
#include <thread>
using namespace std;
class A {
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void funcA() {
cout << "A function()" << endl;
}
};
void thread_Handler(A *pa) {
std::this_thread::sleep_for(std::chrono::seconds(2));
pa->funcA();
}
int main() {
A *pa = new A();
thread t1(thread_Handler, pa);
delete pa;
t1.join();
return 0;
}
上面代碼的問題:
std::this_thread::sleep_for(std::chrono::seconds(2));
后 pa指標已經main 執行緒中delete 掉了,刪掉之后在訪問 funcA()函式是不合理的
應該修改為
void thread_Handler(A *pa) {
std::this_thread::sleep_for(std::chrono::seconds(2));
if(pa所指向的物件是否還有效)
{
pa->funcA();
}
}
//針對上面的場景,我們可以使用強弱智能指標,修改如下
代碼2
#include <iostream>
#include <thread>
using namespace std;
class A {
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void funcA() {
cout << "A function()" << endl;
}
};
void thread_Handler(weak_ptr<A> pa) {
std::this_thread::sleep_for(std::chrono::seconds(2));
shared_ptr<A> ptr = pa.lock();
if (ptr == nullptr) {
cout << "物件已經銷毀了" << endl;
}
else {
ptr->funcA();
}
}
int main() {
{
shared_ptr<A> ptr(new A());
thread t1(thread_Handler, weak_ptr<A>(ptr));
t1.detach();
}
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}

share_ptr
share_ptr是C++11新添加的智能指標,它限定的資源可以被多個指標共享,
只有指向動態分配的物件的指標才能交給 shared_ptr 物件托管,將指向普通區域變數、全域變數的指標交給 shared_ptr 托管,編譯時不會有問題,但程式運行時會出錯,因為不能析構一個并沒有指向動態分配的記憶體空間的指標
weak_ptr
weak_ptr是一種用于解決shared_ptr相互參考時產生死鎖問題的智能指標,如果有兩個shared_ptr相互參考,那么這兩個shared_ptr指標的參考計數永遠不會下降為0,資源永遠不會釋放,weak_ptr是對物件的一種弱參考,它不會增加物件的use_count,weak_ptr和shared_ptr可以相互轉化,shared_ptr可以直接賦值給weak_ptr,weak_ptr也可以通過呼叫lock函式來獲得shared_ptr,
weak_ptr指標通常不單獨使用,只能和 shared_ptr 型別指標搭配使用,將一個weak_ptr系結到一個shared_ptr不會改變shared_ptr的參考計數,一旦最后一個指向物件的shared_ptr被銷毀,物件就會被釋放,即使有weak_ptr指向物件,物件也還是會被釋放,
weak_ptr并沒有多載operator->和operator *運算子,因此不可直接通過weak_ptr使用物件,典型的用法是呼叫其lock函式來獲得shared_ptr示例,進而訪問原始物件,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539022.html
標籤:其他
上一篇:前端和后端字串比較的區別
