A*
,我想将其作为参数传递给 boost::bind
。 boost::bind
被保存在类似于 boost::functions
的 STL 容器中以供稍后处理。我希望确保
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);
无法编译(请参见此处)
auto_ptr<A> pAutoA(pA);
container.push_back(boost::bind(&SomeClass::HandleA, this, boost::ref(pAutoA));
pAutoA已被销毁,正在删除底层的pA。
编辑02
在提到的容器中,我需要存储具有不同参数的各种“回调”。其中一些是指向对象的裸指针。由于代码很旧,我并不总是能够更改它。
编写自己的包装器以在容器中存储回调是最后的手段(也许是唯一的手段),因此会提供悬赏。