Reputation: 1036
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?
Upvotes: 0
Views: 1749
Reputation:
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
.
Upvotes: 2
Reputation: 1515
The default constructor of a shared_ptr results in a null pointer. That's why the result of dereferencing it is undefined. If you would like to get a pointer to a newly created int with a default value of 0, you should try int_ptr my_int_ptr = std::make_shared<int>()
instead.
Upvotes: 1