C ++容器,销毁后会自动删除元素 [英] C++ container which automatically deletes elements when destructed

查看:156
本文介绍了C ++容器,销毁后会自动删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中创建一个引用列表或引用映射,这些引用或映射在元素销毁后会自动删除.这是一个演示该想法的结构.

I would like to create a list or map of references in C++ which automatically deletes its elements upon their destruction. Here is a structure demonstrating the idea.

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
}

我的代码有两件事.当用std :: vector调用push_back()时,它将创建Foo对象的副本.这是不可接受的,因为foos的元素应反映对bar.foo所做的任何更改.其次,即使foos向量可以存储引用,在离开创建bar的作用域之后,也不会从列表中删除Foo对象.理想情况下,我希望在foos销毁后将Foo引用删除.

There are two things wrong with my code. When push_back() is called with a std::vector, it creates a copy of the Foo object. This would be unacceptable since the elements of foos should reflect any changes done upon bar.foo. Secondly, even if the foos vector could store references, the Foo object would not be removed from the list after leaving the scope where bar was created. Ideally, I would like the Foo reference to be removed from foos upon its destruction.

在实施自己的解决方案之前,我很想知道提供此功能的任何第三方库(可能是Boost?),或者我应该使用的任何适当的技术或策略.谢谢!

Before I implement my own solution, I'd love to know of any third party libraries (Boost, possibly?) which offer this, or any proper techniques or strategies I should be using for this. Thanks!

推荐答案

我认为最好的选择是使用弱指针容器. (如果您的编译器由于某种原因不支持C ++ 11或TR1,则在Boost中可用.)

I think the best option is to use a container of weak pointers. (Available in Boost if your compiler doesn't support C++11 or TR1 for some reason.)

假设目标已正确初始化,则当目标被破坏时,弱指针将自动使自身失效.

A weak pointer will automatically invalidate itself when the target is destructed, assuming you initialized things properly.

下面是一些示例代码,用于在弱指针容器中获取所有有效指针.

Here's some sample code for getting all valid pointers in a container of weak pointers.

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;
}

这是清除所有无效指针的方法.

And here's how to clean out all invalid pointers.

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());
}

这篇关于C ++容器,销毁后会自动删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆