Make shared pointer point to a variable

Viewed 1207

Just started working with shared pointers and tried an example program like this:

int x = 10;
shared_ptr<int> ptr = make_shared<int>(x);
*ptr = 11;
cout<< x << " " << *ptr;

The result is 10 11 which didn't make sense to me since ptr was pointing to x and hence the value of x should have been changed to 11. Can someone please explain here? Also I would need the value of x to be changed when a shared pointer to it is changed. Please let me know how I can achieve that as well. Thanks in advance.

3 Answers

You're misunderstanding what std::shared_ptr provides. It is a mechanism for sharing ownership of dynamic data; not attaching pointers to non-dynamic data.

In your posted code, this declares a simple int variable with initial value of 10

int x = 10;

Then this constructs a shared pointer to a new int whose only relationship to x is the value reaped from the latter to initialize the former.

std::shared_ptr<int> ptr = std::make_shared<int>(x);  

In other words, for all intents in this code, the above is equivalent to:

std::shared_ptr<int> ptr = std::make_shared<int>(10);

If you want a bunch of pointers in your code to refer to x by address, first ask yourself why, then ask yourself why you're not just using references. I.e.

int x = 10;

// somewhere else
int &ref = x;
ref = 42; // will change x

If what you really want is a shared state with ownership reference counting and proper disposal mechanics therein, then you probably want:

std::shared_ptr<int> x = std::make_shared<int>(10);

// somewhere else
std::shared_ptr<int> ptr = x;

With the above code, there are two references to a dynamic int : the shared pointer x, and the shared pointer ptr. Both have equal and shared ownership of that dynamic int. When either is destroyed the resource still exists, as it is still referenced by the remaining shared pointer. When the last outstanding reference is destroyed, so too goes the dynamic int.

make_share constructs a new object using parameter passed to it. In this case it's x I guess you would need shared_ptr<int*>. Is that what you want ??

int x = 10;
std::shared_ptr<int*> ptr = std::make_shared<int*>(&x);
**ptr = 11;
std::cout<< x << " " << **ptr;
shared_ptr<int> ptr = make_shared<int>(x);

make_shared<int> constructs an object of type int and wraps it in a std::shared_ptr using args as the parameter list for the constructor of int. So its int value is the value of x; it doesn't point to x.

It's equal to:

shared_ptr<int> ptr = make_shared<int>(10);

--

Also I would need the value of x to be changed when a shared pointer to it is changed.

You can simply make x a shared_ptr<int> and share it. Or you can even just bounce x-reference: &x. So in any place it can by modified. No?

Related