简体   繁体   English

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

[英]Custom deleter in std::unique_ptr not called

Example does not make sense but still cannot explain why custom deleter is not called. 示例没有意义,但仍然无法解释为什么调用自定义删除器。

After the answers I got, I edited my code so myP is not null before smartP goes out of scope 得到答案后,我编辑了代码,以便在smartP超出范围之前myP不为null

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 's destructor will only call its deleter if the contained pointer is not nullptr . 如果所包含的指针不是nullptrunique_ptr的析构函数将仅调用其删除器。

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

Effects: If get() == nullptr there are no effects. 效果: 如果get() == nullptr ,则没有效果。 Otherwise get_deleter()(get()) . 否则get_deleter()(get())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM