【发布时间】:2011-05-11 12:03:48
【问题描述】:
假设我已经分配了堆A*,我想将其作为参数传递给boost::bind。
boost::bind 被保存在一些 STL 中,例如 boost::functions 的容器中以供以后处理。
我想确保 A* 在 STL 容器销毁时被销毁。
演示:
A* pA = new A();
// some time later
container.push_back(boost::bind(&SomeClass::HandleA, this, pA);
// some time later
container is destroyed => pA is destroyed too
怎么做?
编辑
也许我想要的不是那么现实。
我有原始指针和接收原始指针的函数。通过 boost::bind 延迟调用。在这一点上,我想要自动内存管理,以防 boost::bind 想要执行。我很懒,所以我想使用“现成的”智能指针解决方案。
std::auto_ptr 看起来不错,但是 ...
auto_ptr<A> pAutoA(pA);
container.push_back(boost::bind(&SomeClass::HandleA, this, pAutoA);
无法编译(参见here)
auto_ptr<A> pAutoA(pA);
container.push_back(boost::bind(&SomeClass::HandleA, this, boost::ref(pAutoA));
pAutoA 被销毁,删除底层 pA。
编辑 02
在提到的容器中,我需要存储带有不同参数的杂项“回调”。其中一些是指向对象的原始指针。由于代码很旧,我并不总是可以更改它。
为在容器中存储回调编写自己的包装器是最后的手段(虽然可能是唯一的),因此是赏金。
【问题讨论】:
标签: c++ memory-management boost-bind auto-ptr boost-function