首页 > 解决方案 > 未调用 std::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

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

解决方案


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

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

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


推荐阅读