删除()对象指针上的向量是否会破坏对象本身?

时间:2022-11-29 16:57:03

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.

我需要知道擦除物体是否也会破坏它。

5 个解决方案

#1


55  

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.

删除从向量容器中删除并调用它的析构函数,但是如果所包含的对象是一个指针,那么它就不具有销毁它的所有权。

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 & templates as @Billy pointed out in comments:

一个更加通用和优雅的解决方案:这个解决方案使用了for_each和模板,@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, myclassVector is your vector containing pointers to myclass class 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;
}

#2


9  

  • If you have a vector<MyObject> then MyObject::~MyObject will be called.
  • 如果有一个向量 ,则会调用MyObject::~MyObject。
  • If you have a vector<MyObject*> then delete <MyObject instance> will not be called.
  • 如果您有一个向量 ,那么删除 将不会被调用。 实例> *>

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

#3


2  

Yes, erase destroys 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.

是的,擦除破坏元素。但是,如果您将元素放在另一个容器中,您可能会将其复制到另一个容器中。遇到问题的唯一方法是将指针或类似的东西复制到另一个容器中。

#4


2  

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

是的。删除将销毁被删除的对象,这涉及调用它的析构函数。

#5


2  

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

是的,当然会。如果物体不存在于矢量中,它还存在于哪里?

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

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

#1


55  

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.

删除从向量容器中删除并调用它的析构函数,但是如果所包含的对象是一个指针,那么它就不具有销毁它的所有权。

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 & templates as @Billy pointed out in comments:

一个更加通用和优雅的解决方案:这个解决方案使用了for_each和模板,@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, myclassVector is your vector containing pointers to myclass class 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;
}

#2


9  

  • If you have a vector<MyObject> then MyObject::~MyObject will be called.
  • 如果有一个向量 ,则会调用MyObject::~MyObject。
  • If you have a vector<MyObject*> then delete <MyObject instance> will not be called.
  • 如果您有一个向量 ,那么删除 将不会被调用。 实例> *>

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

#3


2  

Yes, erase destroys 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.

是的,擦除破坏元素。但是,如果您将元素放在另一个容器中,您可能会将其复制到另一个容器中。遇到问题的唯一方法是将指针或类似的东西复制到另一个容器中。

#4


2  

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

是的。删除将销毁被删除的对象,这涉及调用它的析构函数。

#5


2  

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

是的,当然会。如果物体不存在于矢量中,它还存在于哪里?

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

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