public member function
<memory>

std::unique_ptr::get_deleter

      deleter_type& get_deleter() noexcept;const deleter_type& get_deleter() const noexcept;
获取存储的删除器
返回存储的删除器

存储的删除器是一个可调用的对象。对此对象的函数调用,接受一个成员类型的单参数指针被期望删除所管理的对象,并在unique_ptr销毁赋值新值重置(当其非空时)时自动调用。

此函数可用于获取或设置删除器。

unique_ptr模板使用的默认删除器类型是default_delete,一个无状态类。

参数



返回值

指向用于删除所拥有指针的存储的删除器的引用(或 const 引用)。
deleter_type是一个成员类型,定义为unique_ptr的第二个模板参数的别名。

示例

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

输出
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]


另见