C++ 对象指针向量上的 vector::erase() 是否会破坏对象本身?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6353149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:58:40  来源:igfitidea点击:

Does vector::erase() on a vector of object pointers destroy the object itself?

c++stlvector

提问by cesar

I have a vector of pointers to objects. I need to remove an element from the vector and place that element in another list.

我有一个指向对象的指针向量。我需要从向量中删除一个元素并将该元素放在另一个列表中。

I read that erase can be used to remove the object from the vector, but I also read that it calls the objects destructor before doing so.

我读到擦除可用于从向量中删除对象,但我也读到它在这样做之前调用了对象析构函数。

I need to know whether or not erasing the object will destroy it as well.

我需要知道擦除对象是否也会破坏它。

回答by Alok Save

vector::erase
Removes from the vector container and calls its destructor but If the contained object is a pointer it doesnt take ownership of destroying it.

vector::erase
从向量容器中移除并调用其析构函数,但如果包含的对象是一个指针,则它不会拥有销毁它的所有权。

You will have to explicitly call delete on each contained pointer to delete the content it is pointing to, for example:

您必须在每个包含的指针上显式调用 delete 以删除它指向的内容,例如:

void clearVectorContents( std::vector <YourClass*> & a ) 
{    
    for ( int i = 0; i < a.size(); i++ ) 
    {       
        delete a[i];    
    }    
    a.clear(); 
} 

Storing raw pointers in standard containers is not a good idea. If you really need to store resources that have to be allocated by new, then you should use boost::shared_ptr. Check out the Boost documentation.

将原始指针存储在标准容器中并不是一个好主意。如果您确实需要存储必须由 分配的资源new,那么您应该使用boost::shared_ptr. 查看Boost 文档

An more generic & elegant solution:
This solution makes use of for_each& templatesas @Billy pointed out in comments:

一个更通用和优雅的解决方案:
这个解决方案使用了for_each&templates正如@Billy 在评论中指出的那样:

// Functor for deleting pointers in vector.
template<class T> class DeleteVector
{
    public:
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(T x) const
    {
        // Delete pointer.
        delete x;
        return true;
    }
};

And this can be called as:

这可以称为:

for_each( myclassVector.begin(),myclassVector.end(),
          DeleteVector<myclass*>());

where, myclassVectoris your vector containing pointers to myclassclass objects.

其中,myclassVector您的向量包含指向myclass类对象的指针。

Usage Example:

用法示例:

#include "functional"
#include "vector"
#include "algorithm"
#include "iostream"

//Your class
class myclass
{
    public:
        int i;
        myclass():i(10){}
};


// Functor for deleting pointers in vector.
template<class T> class DeleteVector
{
    public:
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(T x) const
    {
        // Delete pointer.
        delete x;
        return true;
    }
};


int main()
{
    // Add 10 objects to the vector.
    std::vector<myclass*> myclassVector;

    for( int Index = 0; Index < 10; ++Index )
    {
        myclassVector.push_back( new myclass);
    }

    for (int i=0; i<myclassVector.size(); i++) 
    {
        std::cout << " " << (myclassVector[i])->i;
    }

    // Now delete the vector contents in a single  line.
    for_each( myclassVector.begin(),
              myclassVector.end(),
              DeleteVector<myclass*>());

    //Clear the vector 
    myclassVector.clear();

    std::cout<<"\n"<<myclassVector.size();

    return 0;
}

回答by Tomas Andrle

  • If you have a vector<MyObject>then MyObject::~MyObjectwill be called.
  • If you have a vector<MyObject*>then delete <MyObject instance>will not be called.
  • 如果你有一个vector<MyObject>thenMyObject::~MyObject会被调用。
  • 如果你有,vector<MyObject*>delete <MyObject instance>不会被调用。

To move MyObject between two vectors, you need to first insert it into the destination vector, then erase the original. Note that this will create a new copy of the object. When moving pointers, you can just keep the pointer in a temporary variable, erase it from the vector, then insert wherever you need.

要在两个向量之间移动 MyObject,您需要先将其插入目标向量,然后擦除原始向量。请注意,这将创建对象的新副本。移动指针时,您可以将指针保留在一个临时变量中,将其从向量中删除,然后插入到您需要的任何位置。

And here's another simple way to delete and then remove all the items in a vector:

这是另一种简单的方法来删除然后移除向量中的所有项目:

template<class T> void purge( std::vector<T> & v ) {
    for ( auto item : v ) delete item;
    v.clear();
}

回答by Puppy

Yes, of course it will. If the object doesn't exist in the vector, where else would it exist?

是的,当然会。如果该对象不存在于向量中,那么它还会存在于何处?

Edit: This will notdelete anything pointed to by a pointer. You should use automatic life-time managing pointers such as shared_ptrto manage object lifetimes.

编辑:这不会删除指针指向的任何内容。您应该使用自动生命周期管理指针shared_ptr来管理对象生命周期。

回答by Billy ONeal

Yes, erasedestroys the element. However, if you're placing the element in another container you probably made a copy putting it into that other container. The only way you'd run into issues is if you copied a pointer or something like that into the other container.

是的,erase破坏元素。但是,如果您将元素放置在另一个容器中,您可能制作了一个副本并将其放入另一个容器中。您遇到问题的唯一方法是将指针或类似的东西复制到另一个容器中。

回答by Dominic Gurto

Yes. vector::erasedestroys the removed object, which involves calling its destructor.

是的。vector::erase销毁被移除的对象,这涉及调用其析构函数。