public member function
<memory>

std::weak_ptr::weak_ptr

default (1)
constexpr weak_ptr() noexcept;
copy (2)
weak_ptr (const weak_ptr& x) noexcept;template <class U> weak_ptr (const weak_ptr<U>& x) noexcept;
from shared_ptr (3)
template <class U> weak_ptr (const shared_ptr<U>& x) noexcept;
default (1)
constexpr weak_ptr() noexcept;
copy (2)
weak_ptr (const weak_ptr& x) noexcept;template <class U> weak_ptr (const weak_ptr<U>& x) noexcept;
from shared_ptr (3)
template <class U> weak_ptr (const shared_ptr<U>& x) noexcept;
move (4)
weak_ptr (weak_ptr&& x) noexcept;template <class U> weak_ptr (weak_ptr<U>&& x) noexcept;
Construct weak_ptr
Constructs a weak_ptr object.

If an argument x is passed, and x is not empty, the weak_ptr object becomes part of the owning group of x, giving access to that object's assets until expired without taking ownership itself (and without increasing its use count).

If x is empty, or if no argument is passed, the constructed weak_ptr is empty.

If x is an alias, the weak_ptr preserves both the owned data and the stored pointer.

Parameters

x
A weak_ptr or shared_ptr object.
U* shall be implicitly convertible to T* (where T is weak_ptr's template parameter).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// weak_ptr constructor example
#include <iostream>
#include <memory>

struct C {int* data;};

int main () {
  std::shared_ptr<int> sp (new int);

  std::weak_ptr<int> wp1;
  std::weak_ptr<int> wp2 (wp1);
  std::weak_ptr<int> wp3 (sp);

  std::cout << "use_count:\n";
  std::cout << "wp1: " << wp1.use_count() << '\n';
  std::cout << "wp2: " << wp2.use_count() << '\n';
  std::cout << "wp3: " << wp3.use_count() << '\n';
  return 0;
}

Output:
use_count:
wp1: 0
wp2: 0
wp3: 1


See also