Vor*_*ico 1 c++ destructor reference list
我想在C++中创建一个列表或引用映射,它们会在销毁时自动删除它们的元素.这是一个展示这个想法的结构.
class Foo;
class Bar
{
Foo foo;
};
void main(void)
{
std::vector<Foo> foos;
{
Bar bar;
foos.push_back(bar.foo);
// foos[0] should be the same reference as bar.foo
}
// bar is now destructed
// foos.size() should be 0
}
Run Code Online (Sandbox Code Playgroud)
我的代码有两个问题.当push_back()使用std :: vector调用它时,它会创建Foo对象的副本.这是不可接受的,因为要素foos应反映所做的任何改变bar.foo.其次,即使foos向量可以存储引用,在离开bar创建的范围之后,也不会从列表中删除Foo对象.理想情况下,我希望Foo引用foos在其销毁时被删除.
在我实现自己的解决方案之前,我想知道任何提供此解决方案的第三方库(Boost,可能?),或者我应该使用的任何适当的技术或策略.谢谢!
我认为最好的选择是使用一个弱指针容器.(如果您的编译器出于某种原因不支持C++ 11或TR1,则在Boost中可用.)
假设你正确地初始化了东西,当目标被破坏时,弱指针会自动使自身无效.
下面是一些示例代码,用于在弱指针容器中获取所有有效指针.
template <class T>
std::vector<std::shared_ptr<T> > MassLock(const std::vector<std::weak_ptr<T> >& weakptrs)
{
std::vector<std::shared_ptr<T> > sharedptrs;
for(unsigned int i=0; i<weakptrs.size(); ++i)
{
if (std::shared_ptr<T> temp = weakptrs.at(i).lock())
{
sharedptrs.push_back(temp);
}
}
return sharedptrs;
}
Run Code Online (Sandbox Code Playgroud)
这里是如何清除所有无效指针.
template <class T>
struct isInvalid : public std::unary_function<T, bool>
{
bool operator() (T rhs) { return !rhs.lock(); }
};
template <class T>
void EraseInvalid( std::vector<T>& targetlist )
{
targetlist.erase( remove_if(targetlist.begin(), targetlist.end(), isInvalid<T>() ), targetlist.end());
}
Run Code Online (Sandbox Code Playgroud)