Here is what happens in your code:
int main() { vector<Base> v; // 1 Base b('b'); // 2 Child c; // 3 v.push_back(b); // 4 v.push_back(c); // 5 return 0; } // 6
line 1: the constructed vector v
line 2: base b is built (calling the base constructor)
line 3: constructed child c (call the constructor Child and constructor Base)
line 4: v has maximum bandwidth and needs to be changed.
Memory is allocated for 1 Base by v element.
Base b is copied to v [0] (calling the base copy constructor).
line 5: v again has the maximum capacity and needs to be changed.
Memory is allocated for two Base by v elements.
Old v [0] is copied to new v [0] (the calling constructor of the base copy).
Old v [0] is deleted (calling the base destructor ("base destructor: b")).
Child c is copied to v [1] (calling the base copy constructor).
line 6: c, b and v end.
Child c is deleted (calling Child destructor ("Tree structure detector"), then the base destructor ("Base destructor: c").
Base b is deleted (calling the base destructor ("base destructor: b")).
Databases v [0], v [1] are deleted (Base destructor is called twice ("Base destructor: b", "Base destructor: c")).
No memory leak - for each constructor, the corresponding destructor is called in the specified sequence.
Also, you seem very confused about copy constructors. Child c is passed push_back as Base & - which then calls the base copy constructor as expected. Since the Base implicit copy constructor is not virtual or overridden, having Child from uncopyable does not change anything.
Note that a vector<Base>
cannot store an object of type Child; he knows that he allocates enough memory for the Base. What happens when you assign a Child instance to the database is called slicing, which, although often unintentionally and misunderstood, seems to really be what you want in the scenario you describe.
source share