Overwrite "object managing shared pointer" with new memory C++

49 views Asked by At

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.

1

There are 1 answers

1
Some programmer dude On BEST ANSWER

The first constructor is the construction of the first object.

The second constructor is the construction of the second object.

The first destructor is the destruction of the first object, as part of the assignment to the smart pointer object.

The second destructor is 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:

// Construction of first object
auto classPtr = std::make_shared<TestClass>(100, 200);

// Construction of the second object
auto temporary = std::make_shared<TestClass>(100, 200);

// Assignment, causing destruction of the first object
classPtr = temporary;