std::weak_ptr
#include
#include
std::weak_ptr gw;
void f()
{
if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}
void TestWeakPtrScope_1()
{
std::cout << "TestWeakPtrScope_1" << std::endl;
std::shared_ptr sp1;
{
auto sp = std::make_shared(42);
gw = sp;
f();
sp1 = gw.lock();
}
f();
}
void TestWeakPtrScope_2()
{
std::cout << "TestWeakPtrScope_2" << std::endl;
std::shared_ptr sp1;
{
auto sp = std::make_shared(42);
gw = sp;
f();
}
f();
}
int main()
{
TestWeakPtrScope_1();
TestWeakPtrScope_2();
}
輸出:
TestWeakPtrScope_1
42
42
TestWeakPtrScope_2
42
gw is expired