public member function
<memory>

std::shared_ptr::unique

bool unique() const noexcept;
Check if unique
Returns whether the shared_ptr object does not share ownership over its pointer with other shared_ptr objects (i.e., it is unique).

Empty pointers are never unique (as they do not own any pointers).

Unique shared_ptr objects are responsible to delete their managed object if they release this ownership (see the destructor).

This function shall return the same as (use_count()==1), although it may do so in a more efficient way.

Parameters

none

Return value

true if this is a unique shared_ptr, false otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// shared_ptr::unique
#include <iostream>
#include <memory>

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

  std::cout << "foo unique?\n" << std::boolalpha;

  std::cout << "1: " << foo.unique() << '\n';  // false (empty)

  foo = bar;
  std::cout << "2: " << foo.unique() << '\n';  // false (shared with bar)

  bar = nullptr;
  std::cout << "3: " << foo.unique() << '\n';  // true

  return 0;
}

Output:
foo unique?
1: false
2: false
3: true


See also