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

Custom deleter in std::unique_ptr not called

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

得到答案后,我编辑了我的代码,使 myPsmartP 超出范围之前不为空

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

unique_ptr 的析构函数只会在包含的指针不是 nullptr.

时调用其删除器

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

Effects: If get() == nullptr there are no effects. Otherwise get_deleter()(get()).