c++ - 未调用 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
解决方案
unique_ptr
如果包含的指针不是 , 的析构函数只会调用它的删除器nullptr
。
从 N3337,[unique.ptr.single.dtor] /2
效果: 如果
get() == nullptr
没有效果。否则get_deleter()(get())
。
推荐阅读
- go - Golang os.使用嵌套目录创建路径
- azure - 架构问题 - Azure 服务总线和消息顺序保证
- spring - 为什么Spring的RestTemplate还有setter,Spring也提供了RestTemplateBuilder类来构建RestTemplate
- python - 在 Pandas groupby 中的行中添加新列
- angular - 无法在子组件中共享/触发父组件的点击事件
- java - 如何将反应端口更改为 API 端口?
- postgresql - 为什么我的 postgres 横向子查询失败?
- excel - 试图将 VBA 编码的两部分合二为一
- docker - 为什么 Azure Pipelines Docker 任务 buildContext 为空?
- react-native - Apollo 客户端 devtool 无法在反应本机应用程序中检测到 Apollo 客户端