std::weak_ptr::expired

1
bool expired() const;
(since C++11)

Checks whether the managed object has already been deleted. Equivalent to use_count() == 0.

Parameters

(none).

Return value

true if the managed object has already been deleted, false otherwise.

Exceptions

noexcept specification:
noexcept

Example

Demonstrates how expired is used to check validity of the pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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();
}

Output:

1
2
gw is valid
gw is expired

See also

creates a shared_ptr that manages the referenced object
(public member function)
returns the number of shared_ptr objects that manage the object
(public member function)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.