weak_ptr::lock
取得資源的獨佔擁有權。
shared_ptr<Ty> lock() const;
備註
成員函式傳回空白 shared_ptr 物件 *this 是否過期;否則會傳回擁有資源 *this 指向 shared_ptr 類別的<Ty> 物件。
範例
// std_tr1__memory__weak_ptr_lock.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>
struct deleter
{
void operator()(int *p)
{
delete p;
}
};
int main()
{
std::weak_ptr<int> wp;
{
std::shared_ptr<int> sp(new int(10));
wp = sp;
std::cout << "wp.expired() == " << std::boolalpha
<< wp.expired() << std::endl;
std::cout << "*wp.lock() == " << *wp.lock() << std::endl;
}
// check expired after sp is destroyed
std::cout << "wp.expired() == " << std::boolalpha
<< wp.expired() << std::endl;
std::cout << "(bool)wp.lock() == " << std::boolalpha
<< (bool)wp.lock() << std::endl;
return (0);
}
需求
標頭: <memory>
命名空間: std