天天看點

C++标準庫學習筆記(Weak Pointer)-4

聲明:這個博文所有内容均來自于C++标準庫-自學教程與參考手冊(第二版)英文版 上冊。如果轉載,務必附帶本聲明,并注明出處。

要想使用weak_ptr,需要包含頭檔案< memory>。

在使用shared_ptr的時候如果形成了循環引用的話,被引用的對象會因為計數永遠到不了0而造成記憶體無法釋放。weak_ptr恰好可以解決這個問題,可以打破這種循環引用進而使資源自動釋放,但是使用的時候也必須小心。

你不能使用符号 * 或者 ->來直接擷取一個weak_ptr引用的對象,而是必須建立一個shared_ptr,理由如下:1、在weak_ptr之外再建立一個shared pointer可以檢查這個指針是否還關聯了一個對象。如果沒有,則會抛出異常或者建立一個空指針(具體哪種取決于你的操作)。2、當所引用的對象正在被使用時,shared pointer是不能釋放的。

#include <iostream>
#include <string>
#include <memory>

int main()
{
    try
    {
        std::shared_ptr<std::string> sp(new std::string("Hi sp!"));
        std::weak_ptr<std::string> wp = sp;
        sp.reset();
        std::cout << wp.use_count() << std::endl << wp.expired() << std::endl;
        std::shared_ptr<std::string> p(wp);

    }
    catch (const std::exception & e)
    {
        std::cerr << "exception: " << e.what() << std::endl;
    }
}
           

繼續閱讀