C++ copy constructor clear up on vector<Base*> of Derived* -
i have class uses class of base pointers derived objects, need have own desructor deleting vector's elements , custom copy , assignment funcitons. i'm not entirely sure preferred way of implementing structure below , writing right copy , assignment constructors , destructors it. may ask guide me? i've read lot , searched i'm still not sure.
class base { public: base(); ~virtual base(); int a; int type; // derived1 or derived2 std::string b; ... } class derived1 : public base { public: derived1(); derived1(const base* a); virtual ~derived1(); } class derived1 { derived1::derived1(const base *a) : base(a) { } } class derived2 : public base { public: derived2(); derived2(const base* a); virtual ~derived2(); std::string d1; std::string d2; int d3; } class derived2 { derived2::derived2(const base *a) : base(a) { this->d1 = ((derived2*)a)->d1; this->d2 = ((derived2*)a)->d2; this->d3 = ((derived2*)a)->d3; } } class { public: a(); ~a(); a(const a& a); a& operator = (const a& a); std::string somestring; std::vector<base*> vect; } a::~a() { std::vector<base*>::iterator = vect.begin(); while (it != vect.end()) { delete (*it); it++; } a::a(const &a) { somestring = a.somestring; for(std::size_t = 0; < a.vect.size(); ++i { somestring = a.somestring; base* base = a.vect.at(i); if(base->type == base::typed1) { base = new derived1( a.vect.at(i) ); vect.push_back( base ); } else { base = new derived2( a.vect.at(i) ); vect.push_back( base ); } } }
your loop in destructor fine in practice, , usual solution. formally, undefined behavior, since leaving objects in vector (pointers deleted objects) aren't copiable, in practice: vector won't copy them unless resize bigger, or insert or erase on it. if want avoid undefined behavior:
for ( auto current = vect.begin(); current != vect.end(); ++ current ) { base* tmp = *it; *it = nullptr; delete tmp; }
but 1 case wouldn't bother (and tend more sensitive undefined behavior most).
Comments
Post a Comment