public member function
<memory>

std::unique_ptr::get_deleter

      deleter_type& get_deleter() noexcept;const deleter_type& get_deleter() const noexcept;
Get stored deleter
Returns the stored deleter.

The stored deleter is a callable object. A functional call to this object with a single argument of member type pointer is expected to delete the managed object, and is automatically called when the unique_ptr is itself destroyed, assigned a new value, or resetted while non-empty.

This function can be used to either get or set the deleter.

The default deleter type used by the unique_ptr template is default_delete, a stateless class.

Parameters

none

Return value

A reference (or const reference) to the stored deleter used to delete the owned pointer.
deleter_type is a member type, defined as an alias of unique_ptr's second template parameter.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// unique_ptr deleter with state
#include <iostream>
#include <memory>

class state_deleter {  // a deleter class with state
  int count_;
public:
  state_deleter() : count_(0) {}
  template <class T>
  void operator()(T* p) {
    std::cout << "[deleted #" << ++count_ << "]\n";
    delete p;
  }
};

int main () {
  state_deleter del;

  std::unique_ptr<int> p;   // uses default deleter

  // alpha and beta use independent copies of the deleter:
  std::unique_ptr<int,state_deleter> alpha (new int);
  std::unique_ptr<int,state_deleter> beta (new int,alpha.get_deleter());

  // gamma and delta share the deleter "del" (deleter type is a reference!):
  std::unique_ptr<int,state_deleter&> gamma (new int,del);
  std::unique_ptr<int,state_deleter&> delta (new int,gamma.get_deleter());

  std::cout << "resetting alpha..."; alpha.reset(new int);
  std::cout << "resetting beta..."; beta.reset(new int);
  std::cout << "resetting gamma..."; gamma.reset(new int);
  std::cout << "resetting delta..."; delta.reset(new int);

  std::cout << "calling gamma/delta deleter...";
  gamma.get_deleter()(new int);

  alpha.get_deleter() = state_deleter();  // a brand new deleter for alpha

  // additional deletions when unique_ptr objects reach out of scope
  // (in inverse order of declaration)

  return 0;
}

Output:
resetting alpha...[deleted #1]
resetting beta...[deleted #1]
resetting gamma...[deleter #1]
resetting delta...[deleter #2]
calling gamma/delta deleter...[deleted #3]
[deleted #4]
[deleted #5]
[deleted #2]
[deleter #1]


See also