[英]Once a lock on std::weak_ptr has returned nullptr, can it ever be non-null again?
如果你對std::weak_ptr
采取鎖定:
class foo {};
auto s = std::make_shared<foo>();
std::weak_ptr<foo> w{ s };
s = nullptr;
s.reset(new foo());
auto l = w.lock(); // try to get previous foo
std::cout << "locked: " << (l != nullptr) << std::endl;
輸出:
locked: 0
一旦lock返回nullptr
,是否有一個條件可以返回非null,或者它是否有效死了?
我的測試程序建議,一旦最初分配的對象的引用計數為零,則為no, weak_ptr
將始終返回nullptr。
它是否存在可以返回非空的每一個條件,或者它是否有效地死了?
嗯,那時“幾乎”死了。 lock
調用以與此相當的方式expired
:
expired() ? shared_ptr<T>() : shared_ptr<T>(*this)
然后,查看到期條件:
相當於
use_count() == 0
。 可能尚未調用托管對象的析構函數,但此對象的破壞即將發生(或者可能已經發生)。
無論哪種方式,都不可能將特定的weak_ptr
重新分配給另一個值。
#include <iostream>
#include <memory>
int
main()
{
using namespace std;
shared_ptr<int> p(new int{3});
weak_ptr<int> w = p;
p = nullptr;
auto l = w.lock();
if (l == nullptr)
cout << "l = nullptr\n";
else
cout << "l = " << *l << '\n';
p.reset(new int{4});
w = p;
l = w.lock();
if (l == nullptr)
cout << "l = nullptr\n";
else
cout << "l = " << *l << '\n';
}
便攜式輸出:
l = nullptr
l = 4
所以,是的,如果weak_ptr
是從非空的shared_ptr
分配的,那么它可以“從死里復活”。
也許這不是你的意思。 但這就是你的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.