Search code examples
c++11shared-ptr

shared pointer in constructor initializer list


I created a shared pointer like below

typedef std::shared_ptr<int> int_ptr;
int main()
{
   int_ptr my_int_ptr();
   std::cout << *my_int_ptr << std::endl;
}

The output of this code is 1. I am not sure how come 1 is getting is printed. Is it some garbage it is printing?

Okie as of now it printed some value, that means proper memory exist for it.

Now applying this same concept, but this time my shared pointer is a member of class and I am initializing it in constructor member initializer list. Code is below.

typedef std::shared_ptr<int> int_ptr;
class MyInt
{

public:
    MyInt():m_myint_ptr(){
    }   

    void show() { 
    std::cout << *m_myint_ptr << std::endl; 
    }

private:
    int_ptr m_myint_ptr;
};

int main()
{
    MyInt my_int;
    my_int.show();
}

But this time I got segmentation fault when show function is called and shared pointer is dereferenced.

I am not able to understand whats going under the hood.

Could somebody help me with following questions?

  1. How does 1 is getting printed?
  2. Why segmentation fault is happening?

Solution

  • The segmentation fault for accessing a unassigned shared_ptr<> is perfectly normal, as you are essentially dereferencing null.

    The interesting bit is why your first test did not crash.

    int_ptr my_int_ptr();
    

    This line of code does not do what you think it does. You are forward declaring a function called my_int_ptr that returns an int_ptr, not declaring a default-initialized instance of int_ptr.