c++ - Adding Elements to std::vector of an abstract class -
i want store objects of classes derived common interface (abstract class) in std::vector of abstract class. vector should filled in loop , call constructor of class , push created object vector.
as understand, in case of abstract class can store pointers class, need push_back pointers of derived classes. however, not sure scope of these newly created objects.
please, have @ code below. code compiles , works fine questions are:
a) objects guaranteed exist in second for-loop in main function? or might cease existing beyond scope of loop in created?
b) objects' destructors called or might there memory leaks?
#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; }
this perfect case smart pointers. can store pointers in unique_ptr
raii type. when unique_ptr
goes out of scope autmaticlly delete memory you.
//... 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 loop { e->f(); std::cout << e->x << '\t' << std::endl; } // no need here. vector rid of each unique_ptr , each unique_ptr delete each pointer return 0; }
Comments
Post a Comment