weak_ptr
weak_ptr會指向一個share_ptr(使用一個share_ptr來初始化weak_ptr),但并不會增加這個share_ptr的引用計數器,其析構也不會減少share_ptr的引用計數器。
構造函數及使用
#include <iostream>
#include <memory>
#include <string>
#include "StrBlob.h"
#include <stdio.h>int main()
{auto sp = std::make_shared<std::string>("Share");//////////////// 構造函數// 使用shared_ptr來初始化weak_ptr 但要保證sp指向的類型可以轉換為std::stringstd::weak_ptr<std::string> wp1(sp);// 也可直接賦值 同樣要保證sp指向的類型可以轉換為std::stringstd::weak_ptr<std::string> wp2 = sp;// sp的引用計數器仍然為1std::cout << sp.use_count() << std::endl;////////////////// 使用// weak_ptr使用時 要通過lock函數來獲取share_ptr 才能正常使用所指向的對象std::shared_ptr<std::string> spLock = wp1.lock();if (spLock) { // 要判斷該share_ptr是否還有效std::cout << *spLock << std::endl;}return 0;
}