What is the difference between initializing shared_ptr with just another pointer and initializing it with the get method?


There is a process function:

void process(std::shared_ptr<int> sh_ptr) {}

What is the difference between the two process function calls?

std::shared_ptr<int> p(new int(42));
// process(std::shared_ptr<int>(p));
// process(std::shared_ptr<int>(p.get()));

Can you explain what exactly happens in both calls?
I can’t figure out what the get method is for

My thoughts:
As I understand it, the first call to the process function passes it a temporary pointer shared_ptr, which points to int, just like the p pointer. Inside the process function the counter will be 2, after leaving the function, p will be the only pointer and the counter will be 1. Everything seems to be correct. Correct me if I’m wrong

What happens in the second case is not clear to me and I’d like to figure it out.

>Solution :

Lets illustrate it:

You create a pointer to an int value:

int* p1 = new int(some_value);

That will look something like this:

+----+      +------------------+
| p1 | ---> | int (some_value) |
+----+      +------------------+

Then what you’re doing is creating a second pointer, initialized to point to the same location:

int* p2 = p1;

That will then look something like this:

| p1 | -\
+----+  |    +------------------+
         >-> | int (some_value) |
+----+  |    +------------------+
| p2 | -/

This is really what happens when you do shared_ptr<int>(p.get()).

Now lets delete the second pointer:

delete p2;

This deletion is what happens when the temporary shared object is destructed. And that leaves you with this:

| p1 | ---> ???

because the memory allocated for p1 was deleted using p2.

With your code you create two distinct and different pointers, that both point to the same memory but which don’t share any state. Both the smart pointers will think they have exclusive ownership of the memory, and they don’t know anything about each other.

Leave a Reply Cancel reply