首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::weak_ptr

Defined in header <memory>

?

?

template< class T > class weak_ptr;

?

(since C++11)

std::weak_ptr是一个智能指针,它保存不拥有的%28“弱”%29引用,该对象由std::shared_ptr它必须转换成std::shared_ptr以访问引用的对象。

std::weak_ptr模型临时所有权:当一个对象只有在存在时才需要被访问,并且它可能在任何时候被其他人删除,std::weak_ptr用于跟踪对象,并将其转换为std::shared_ptr暂时拥有。如果原std::shared_ptr此时,对象%27s的生存期将延长到std::shared_ptr也被摧毁了。

此外,std::weak_ptr的循环引用。std::shared_ptr...

成员类型

Member type

Definition

element_type

T (until C++17) std::remove_extent_t<T> (since C++17)

T

(until C++17)

std::remove_extent_t<T>

(since C++17)

T

(until C++17)

std::remove_extent_t<T>

(since C++17)

成员函数

(constructor)

creates a new weak_ptr (public member function)

(destructor)

destroys a weak_ptr (public member function)

operator=

assigns the weak_ptr (public member function)

修饰符

重置释放托管对象%28公共成员函数%29的所有权

交换托管对象%28公共成员函数%29

观察员

使用[医]计数返回共享的数目。[医]管理对象%28公共成员函数%29的PTR对象

过期检查引用对象是否已被删除%28公共成员函数%29

锁创建共享[医]管理引用对象%28公共成员函数%29的PTR

业主[医]提供基于所有者的弱指针排序%28公共成员函数%29

非会员职能

std::swap(std::weak_ptr) (C++11)

specializes the std::swap algorithm (function template)

演示如何使用锁确保指针的有效性。

二次

代码语言:javascript
复制
#include <iostream>
#include <memory>
 
std::weak_ptr<int> gw;
 
void f()
{
    std::cout << "use_count == " << gw.use_count() << ": ";
    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";
    }
}
 
int main()
{
    {
        auto sp = std::make_shared<int>(42);
        gw = sp;
 
        f();
    }
 
    f();
}

二次

产出:

二次

代码语言:javascript
复制
use_count == 1: 42
use_count == 0: gw is expired

二次

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com