I have a simple code which looks like this, which I was experimenting -
#include<iostream>
#include<memory>
class TestClass {
public:
TestClass(int a, int b) : mA(a), mB(b) {
std::cout << "constructor" << std::endl;
}
~TestClass() { std::cout << "destructor" << std::endl; }
private:
int mA;
int mB;
};
int main(){
auto classPtr = std::make_shared<TestClass>(100, 200);
// Process....
classPtr = std::make_shared<TestClass>(100, 200);
return 0;
}
I overwrite a shared pointer which already manages an object with new memory. Based on my reading of assignement operator for shared pointer https://en.cppreference.com/w/cpp/memory/shared_ptr/operator%3D#:~:text=If,the%20owned%20deleter., the previous memory gets destroyed before the new assignment takes place.
So I expect output to be -
constructor
destructor
constructor
destructor
But the output is -
constructor
constructor
destructor
destructor
Question - I am curious what is happening to the old memory and why it is not de-allocated before the second allocation.
The first
constructoris the construction of the first object.The second
constructoris the construction of the second object.The first
destructoris the destruction of the first object, as part of the assignment to the smart pointer object.The second
destructoris the destruction of the second object, when the variable goes out of scope.The second object must be constructed before an assignment can be made.
Your code is basically equivalent to: