std::weak_ptr::weak_ptr

From cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
 
constexpr weak_ptr();
(1) (since C++11)
weak_ptr( const weak_ptr& r );
(2) (since C++11)
template< class Y >
weak_ptr( const weak_ptr<Y>& r );
(2) (since C++11)
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r );
(2) (since C++11)
weak_ptr( weak_ptr&& r );
(3) (since C++14)
template< class Y >
weak_ptr( weak_ptr<Y>&& r );
(3) (since C++14)

Constructs new weak_ptr that potentially shares an object with r.

1) Default constructor. Constructs empty weak_ptr.
2) Constructs new weak_ptr which shares an object managed by r. If r manages no object, *this manages no object too. The templated overloads don't participate in the overload resolution unless Y* is implicitly convertible to T* , or Y is the type "array of N U" for some type U and some number N, and T is the type "array of unknown bound of (possibly cv-qualified) U". (since C++17)
3) Move constructors. Moves a weak_ptr instance from r into *this. After this, r is empty and r.use_count()==0. The templated overload doesn't participate in the overload resolution unless Y* is implicitly convertible to T*

Contents

[edit] Parameters

r - a std::shared_ptr or std::weak_ptr that will be viewed by this std::weak_ptr

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Example

#include <memory>
#include <iostream>
 
struct Foo {};
 
int main()
{
   std::weak_ptr<Foo> w_ptr;
 
   {
      auto ptr = std::make_shared<Foo>();
      w_ptr = ptr;
      std::cout << "w_ptr.use_count() inside scope: " << w_ptr.use_count() << '\n';
   }
 
   std::cout << "w_ptr.use_count() out of scope: " << w_ptr.use_count() << '\n';
   std::cout << "w_ptr.expired() out of scope: " << std::boolalpha << w_ptr.expired() << '\n';
}

Output:

w_ptr.use_count() inside scope: 1
w_ptr.use_count() out of scope: 0
w_ptr.expired() out of scope: true

[edit] See also

assigns the weak_ptr
(public member function)