public member function
<memory>

std::shared_ptr::~shared_ptr

~shared_ptr();
Destroy shared_ptr
Destroys the object. But, before, it may produce the following side effects depending on the value of member use_count:

  • If use_count is greater than 1 (i.e., the object is sharing ownership of its managed object with other shared_ptr objects): The use count of the other objects with which it shares ownership is decreased by 1.
  • If use_count is 1 (i.e., the object is the unique owner of the managed pointer): the object pointed by its owned pointer is deleted (if the shared_ptr object was constructed with a specefic deleter, this is called; Otherwise, the function uses operator delete).
  • If use_count is zero (i.e., the object is empty), this destructor has no side effects.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// shared_ptr destructor example
#include <iostream>
#include <memory>

int main () {
  auto deleter = [](int*p){
    std::cout << "[deleter called]\n"; delete p;
  };

  std::shared_ptr<int> foo (new int,deleter);

  std::cout << "use_count: " << foo.use_count() << '\n';

  return 0;                        // [deleter called]
}

Output:

use_count: 1
[deleter_called]


See also