Just see code
class SomeClass {
private:
int i;
public:
int getI() {
return i;
}
SomeClass() {
i = 0;
}
explicit SomeClass(int i) {
this->i = i;
}
~SomeClass(){
cout << "SomeClass destructed with i=" << i << "." << endl;
}
};
And the main function
int main() {
auto* someClasses = new SomeClass[5];
someClasses[2] = SomeClass(20);
cout << "A new SomeClass Assigned." << endl;
someClasses[2] = SomeClass(40);
cout << "A new SomeClass Assigned." << endl;
delete[] someClasses;
}
The array is initialized with all objects constructed with i=0, and we do some modification to someClasses[2].
When ending up an object, the destructor of the object should be called. However, the result shows that the destructor is not being invoked.
SomeClass destructed with i=20. // destructed after copy constructor is done.
A new SomeClass Assigned.
SomeClass destructed with i=40. // destructed after copy constructor is done.
A new SomeClass Assigned.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=40. // okay.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=0. // okay.
Process finished with exit code 0
If the destructor is designed not be called in this situation, how to assign a new object correctly to an existed array?
Using an object pointer array is an option but I'm just curious.