std::weak_ptr<T>::expired

来自cppreference.com
 
 
内存管理库
分配器
内存资源
未初始化存储 (C++20 前*)
垃圾收集器支持 (C++23 前)
 
 
bool expired() const noexcept;
(C++11 起)
(C++26 起为 constexpr)

检查被管理对象是否已被删除。可能仍未对被管理对象调用析构函数,但此对象的析构已经临近(或可能已发生)。

返回值

use_count() == 0

注解

如果被管理对象在线程间共享,那么只有 expired() 返回 true 时才有意义。

示例

演示如何用 expired 检查指针的有效性。

#include <iostream>
#include <memory>

std::weak_ptr<int> gw;

void f()
{
    if (!gw.expired())
	    std::cout << "gw 有效\n";
    else
        std::cout << "gw 已过期\n";
}
 
int main()
{
    {
        auto sp = std::make_shared<int>(42);
	    gw = sp;
        f();
    }
    
    f();
}

输出:

gw 有效
gw 已过期

参阅

创建管理被引用的对象的 shared_ptr
(公开成员函数) [编辑]
返回管理该对象的 shared_ptr 对象数量
(公开成员函数) [编辑]
Morty Proxy This is a proxified and sanitized view of the page, visit original site.