Namespaces
Variants

std::weak_ptr<T>:: expired

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
bool expired ( ) const noexcept ;
(自 C++11 起)

等价于 use_count ( ) == 0 。被管理对象的析构函数可能尚未被调用,但该对象的析构已迫在眉睫(或可能已经发生)。

目录

参数

(无)

返回值

true 表示托管对象已被删除, false 表示未被删除。

注释

如果托管对象在线程间共享,仅当 expired() 返回true时才有意义。

示例

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

#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
    if (!gw.expired())
	std::cout << "gw is valid\n";
    else
        std::cout << "gw is expired\n";
}
int main()
{
    {
        auto sp = std::make_shared<int>(42);
	gw = sp;
	f();
    }
    f();
}

输出:

gw is valid
gw is expired

参见

创建管理被引用对象的 shared_ptr
(公开成员函数)
返回管理该对象的 shared_ptr 对象数量
(公开成员函数)