vector :: erase()对象指针的向量会毁坏对象本身? [英] Does vector::erase() on a vector of object pointers destroy the object itself?
问题描述
我有一个指向对象的向量。我需要从向量中删除一个元素,并将该元素放在另一个列表中。
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.
推荐答案
vector :: erase
从向量容器中删除并调用其析构函数,但如果包含的对象是一个指针所有权销毁它。
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.
您必须在每个包含的指针上显式调用delete,才能删除指向的内容,例如:
You will have to explicitly call delete on each contained pointer to delete the content it is pointing to, for example:
void clearVectorContents( std::vector <YourClass*> & a )
{
for ( int i = 0; i < a.size(); i++ )
{
delete a[i];
}
a.clear();
}
将原始指针存储在标准容器中不是一个好主意。如果你真的需要存储由 new
分配的资源,那么你应该使用 boost :: shared_ptr
。请查看 Boost文档。
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.
更通用&优雅的解决方案:
此解决方案使用 for_each
& templates
as @Billy在注释中指出:
An more generic & elegant solution:
This solution makes use of for_each
& templates
as @Billy pointed out in comments:
// 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;
}
};
这可以调用:
for_each( myclassVector.begin(),myclassVector.end(),
DeleteVector<myclass*>());
其中, myclassVector
到 myclass
类对象。
用法示例:
#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;
}
这篇关于vector :: erase()对象指针的向量会毁坏对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!