我有一个指向对象的指针向量.我需要从向量中删除一个元素并将该元素放在另一个列表中.
我读到擦除可用于从向量中删除对象,但我也读到它在这样做之前调用了对象析构函数.
我需要知道擦除对象是否也会破坏它.
我有一个指向对象的指针向量.我需要从向量中删除一个元素并将该元素放在另一个列表中.
我读到擦除可用于从向量中删除对象,但我也读到它在这样做之前调用了对象析构函数.
我需要知道擦除对象是否也会破坏它.
vector::erase
从向量容器中移除并调用其析构函数,但如果包含的对象是一个指针,则它不会拥有销毁它的所有权.
您必须对每个包含的指针显式调用 delete 以删除它指向的内容,例如:
void clearVectorContents( std::vector <YourClass*> & a ) { for ( int i = 0; i < a.size(); i++ ) { delete a[i]; } a.clear(); }
在标准容器中存储原始指针不是一个好主意.如果你真的需要存储必须由new分配的资源,那么你应该使用boost::shared_ptr.查看 Boost 文档.
更通用的 &优雅的解决方案:
此解决方案使用 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; } };
这可以称为:
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<<" "<<myclassVector.size(); return 0; }
这篇关于对象指针向量上的 vector::erase() 是否会破坏对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持前端之家!