std::weak_ptr - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::weak_ptr

From cppreference.com
< cpp‎ | memory

Defined in header `<memory>` |  |
template< class T > class weak_ptr; |  | (since C++11)

`std::weak_ptr` is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.

std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.

In addition, std::weak_ptr is used to break circular references of std::shared_ptr.

### [edit] Member types

Member type | Definition
element_type | T

### [edit] Member functions

(constructor) | creates a new `weak_ptr` (public member function) [edit]
(destructor) | destroys a `weak_ptr` (public member function) [edit]
operator= | assigns the `weak_ptr` (public member function) [edit]
##### Modifiers
reset | releases the ownership of the managed object (public member function) [edit]
swap | swaps the managed objects (public member function) [edit]
##### Observers
use_count | returns the number of `shared_ptr` objects that manage the object (public member function) [edit]
expired | checks whether the referenced object was already deleted (public member function) [edit]
lock | creates a `shared_ptr` that manages the referenced object (public member function) [edit]
owner_before | provides owner-based ordering of weak pointers (public member function) [edit]

### [edit] Non-member functions

std::swap(std::weak_ptr) (C++11) | specializes the std::swap algorithm (function template) [edit]

### [edit] Example

Demonstrates how lock is used to ensure validity of the pointer.

Run this code

    #include <iostream>
    #include <memory>

    std::weak_ptr<int> gw;

    void f()
    {
        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();
    }

Output:

    42
    gw is expired

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/memory/weak_ptr&oldid=69991"