Namespaces
Variants
Views
Actions

std::weak_ptr::weak_ptr

From cppreference.com
< cpp‎ | memory‎ | weak ptr
Revision as of 14:28, 2 November 2012 by P12bot (Talk | contribs)

 
 
 
 
 

Template:ddcl list begin <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
constexpr weak_ptr();
</td>

<td > (1) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
weak_ptr( const weak_ptr& r );
</td>

<td > (2) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class Y >
weak_ptr( const weak_ptr<Y>& r );
</td>

<td > (2) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r );
</td>

<td > (2) </td> <td > (since C++11) </td> </tr> Template:ddcl list end

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*.

Contents

Parameters

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

Exceptions

noexcept specification:  
noexcept
  

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';
}

Output:

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

See also

Template:cpp/memory/weak ptr/dcl list operator=