我想在一个抽象类的std :: vector中存储从公共接口(抽象类)派生的类的对象.这个向量应该填充一个循环,通常我会调用一个类的构造函数并将创建的对象推送到向量中.
据我所知,在抽象类的情况下,我只能存储指向该类的指针,所以我需要push_back派生类的指针.但是,我不确定这些新创建的对象的范围.
a)对象是否保证存在于main函数的第二个for循环中?或者他们可能会停止存在超出创建它们的循环范围?
#include<vector> #include<iostream> class Interface { public: Interface( int y ) : x(y) {} virtual ~Interface() {} virtual void f() = 0; int x; }; class Derived_A : public Interface { public: Derived_A( int y ) : Interface(y) {} void f(){ return; } }; class Derived_B : public Interface { public: Derived_B( int y ) : Interface(y) {} void f(){ return; } }; int main() { std::vector<Interface*> abstractObjects; int N = 5; for(int ii = 0; ii < N; ii++ ) { abstractObjects.push_back( new Derived_A(ii) ); abstractObjects.push_back( new Derived_B(ii) ); } for(int ii = 0; ii < abstractObjects.size(); ii++ ) { abstractObjects[ii]->f(); std::cout << abstractObjects[ii]->x << '\t' << std::endl; } for(int ii = 0; ii < abstractObjects.size(); ii++ ) { delete abstractObjects[ii]; } return 0; }
解决方法
这是智能指针的完美案例.您可以将指针存储在一个RAII类型的
unique_ptr
中.当unique_ptr超出范围时,它将自动为您删除内存.
//... std::vector<std::unique_ptr<Interface>> abstractObjects; int N = 5; for(int ii = 0; ii < N; ii++ ) { abstractObjects.push_back( std::make_unique<Derived_A>(ii) ); abstractObjects.push_back( std::make_unique<Derived_B>(ii) ); } for(auto & e : abstractObjects) // ranged based for loop { e->f(); std::cout << e->x << '\t' << std::endl; } // no need to do anything here. the vector will get rid of each unique_ptr and each unique_ptr will delete each pointer return 0; }