Search code examples
c++stlsmart-pointers

Shared_pointer showing different behaviour than the one i read in text book


So i am trying to develop my understanding of shared_ptr and if multiple shared ptr point at the same resource shared pointer is resposible to handle the case where destrcutor should neve be called before the last pointer pointing at the resource is destroyed.

Here is my sample code:

#include <iostream>
#include <memory>
class A {
public:
    A(int num) {
        std::cout << "cons A\n";
    }
    ~A() {
        std::cout << "dis A\n";
    }
};

int main() {
    std::shared_ptr<A> ptr(new A(12));
    {
        std::cout << "Inside Scope \n";
        std::shared_ptr<A> ptr1 = ptr;
        std::cout << "Outside Scope \n";
    }
    std::shared_ptr<A> ptr2(ptr.get());
    std::cout << ptr << std::endl;
}

And the output with exception being thrown is given below

cons A
Inside Scope 
Outside Scope 
dis A
dis A
free(): double free detected in tcache 2

Can anybody explain this behaviour or i am misreading anything ? Thanks in advance.


Solution

  • The problem is with your line

    std::shared_ptr<A> ptr2(ptr.get());
    

    It is not the way shared pointers should be used. Instead, replace it with something like

    std::shared_ptr<A> ptr2{ptr};
    

    or

    std::shared_ptr<A> ptr2 = ptr;
    

    (Furthermore, as Den-Jason notes in the comment, you should prefer to use std::make_shared.)


    When you pass a naked pointer to ptr2, it has no way of "knowing" that another shared pointer, in this case, ptr, is handling it. It "thinks" that you're passing something you just allocated. Due to this, both of them try to deallocate the same pointer, resulting in the "double free" error you observed.

    Once a shared pointer is managing a resource, you should avoid as much as possible dealing with the naked pointer, and definitely not pass it on to another one.