未调用std :: unique_ptr中的自定义删除器

siw*_*mas 2 c++ unique-ptr c++11

示例没有意义,但仍然无法解释为什么调用自定义删除器.

在得到答案之后,我编辑了我的代码,因此myPsmartP超出范围之前不是null

int * myP = NULL;

{ 
   std::unique_ptr<int, std::function<void(int*)>> smartP(myP, [](int * a) {
        *a = 8; // Custom deleter that is trying to dereference NULL never called
   }); 

   int a = 9;       
   myP = &a;

} // smartP goes out of scope, I expect custom deleter to be called
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 6

unique_ptr如果包含的指针不是,那么析构函数只会调用它的删除器nullptr.

来自N3337,[unique.ptr.single.dtor]/2

效果: 如果get() == nullptr没有效果.否则get_deleter()(get()).

  • @siwmas因为`unique_ptr`没有对'myP`本身持*引用*,而是对其值的*copy*.`unique_ptr`是用空指针值构造的.之后更改`myP`的值不会更改`unique_ptr`在内部保存的指针的值.当`myP`改变值时,你需要用一个新的指针值'reset()``unique_ptr`,例如:`myP =&a; smartP.reset(MYP);` (2认同)