示例没有意义,但仍然无法解释为什么不调用自定义删除器。
得到答案后,我编辑了我的代码,使 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
最佳答案
unique_ptr
的析构函数只会在包含的指针不是 nullptr
时调用其删除器。
来自 N3337,[unique.ptr.single.dtor]/2
Effects: If
get() == nullptr
there are no effects. Otherwiseget_deleter()(get())
.
关于c++ - 未调用 std::unique_ptr 中的自定义删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50988569/