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

时间:2018-06-22 13:03:04

标签: c++ c++11 unique-ptr

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

得到答案后,我对代码进行了编辑,以便在myP超出范围之前,smartP不为空

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

1 个答案:

答案 0 :(得分:6)

unique_ptr的析构函数仅在包含的指针不是nullptr时才调用其删除程序。

从N3337,[unique.ptr.single.dtor]/2

  

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

相关问题