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

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

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

得到答案后,我编辑了我的代码,使 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()).

关于c++ - 未调用 std::unique_ptr 中的自定义删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50988569/

相关文章:

c++ - C 中的后台作业(在玩具外壳中实现 &)

c++ - 为什么 std::lock 不支持超时?

c++ - 将unique_ptr vector 分配给 vector C++

c++ - 无法将标准数组初始化为标准 vector

c++ - 返回元组时如何转移 unique_ptr 的所有权?

c++ - 单元测试、模拟和 unique_ptr

c++ - 在 C++ 中将函数作为参数传递

java - 从 basic_string 到 jstring 的转换

c++ - 查看 std::future 是否已经启动

c++ - 将 lua 表从 C++ 传递到 .Lua 脚本