1
 class Class {
 public:
     Class()  {std::cout << "Constructor" << '\n';}
     ~Class() {std::cout << "Destructor" << '\n';}
 }; 

 int main() {
     std::cout<<"\nNew shared_ptr:\n";
     Class C;
     std::shared_ptr<Class> ptr(&C);
 }

After running I have:

New shared_ptr: 
Constructor 
Destructor 
Destructor

Why is that? Why is the destructor called twice?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
shady9644
  • 11
  • 1

2 Answers2

0

Raw pointers in C++ stores the address of the object (point to the object), whereas smart pointers in C++ act as a wrapper around the raw pointer with automatic delete feature.

Though smart pointers usually do not replicate raw objects but in your case you are passing the address of local C as a parameter, therefore the copy of C gets stored in the heap.

To sum up Class C; uses stack memory whereas std::shared_ptr<Class> ptr(&C); uses heap memory.

At the end of the main() function, the C goes out of scope, therefore destructor is called.

Then the shared pointer deletes its object in the heap automatically, so its corresponding destructor is called.

Therefore two destructor.

Adarsh Kumar
  • 467
  • 6
  • 11
  • 2
    There's no copy. `ptr` tries to take ownership of `C`, which is already owned by `main`. A double destruction of the same object and undefined behaviour ensue. – Quentin Oct 21 '19 at 22:52
0

Giving a raw pointer to a std::shared_ptr, without also using a custom deleter, means that the shared_ptr implementation will delete that pointer value after no more shared_ptr own the pointer. In your example, this happens at the end of main when ptr is destroyed, so it attempts to delete a pointer equal to &C. This is only valid for a pointer that came from a new expression. But the pointer did not come from new; it's just the address of a local variable defined in main. So this is undefined behavior.

aschepler
  • 70,891
  • 9
  • 107
  • 161