You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用带自定义删除器的std::unique_ptr如何避免冗余变量?

如何用std::unique_ptr实现RAII自动清理时避免冗余变量?

我希望使用std::unique_ptr实现自动清理(RAII机制),但初始化该智能指针时需要提供一个指向的地址,请问如何避免代码中的noUse这类冗余变量?

初始代码:

bool noUse;
auto deleter = [](bool *){ DESTROY_SOMETHING }; 
std::unique_ptr<bool, decltype(deleter)> upp(&noUse, deleter); // 我想避免使用这个多余的noUse变量
START_SOMETHING

//复杂的IF ELSE返回逻辑

更新说明:
最终我采用了如下代码,感谢各位的快速回复。

auto deleter = [](void *){ DESTROY_SOMETHING };
std::unique_ptr<void, decltype(deleter)> upp(nullptr, deleter);

if(enabled)
{
   //START_SOMETHING
   upp.reset(reinterpret_cast<void*>(&upp));
}

//复杂的IF ELSE返回逻辑

内容的提问来源于stack exchange,提问作者Mohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:47:17