Assigning existing values to smart-ptrs?

bluepanda picture bluepanda · Nov 25, 2013 · Viewed 28.6k times · Source

I am just learning about smart pointers, and I am having trouble assigning a pre-existing location of a variable to the standard library's shared pointer.

For example, lets say you have an int x, which you do not know the value of. With normal pointers, I just did

int* ptr;
ptr = &x;

I tried both that with shared pointers, and

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

So i'm fairly lost as to how to do it.

Answer

Mike Seymour picture Mike Seymour · Nov 25, 2013

You wouldn't (usually) make a smart pointer point to an existing variable. A smart pointer manages the lifetime of a dynamically allocated object, deleting it after use; pointing it to something that wasn't dynamically allocated will cause an error if it tries to delete it.

You would usually use new or make_shared to create an object, and create or assign a smart pointer with the result of that:

std::shared_ptr<int> ptr(new int(42)); // Create a new pointer to manage an object
ptr.reset(new int(66));                // Reset to manage a different object
ptr = std::make_shared<int>(53);       // Use `make_shared` rather than `new`

make_shared is usually preferable to new, since it makes better use of memory and gives stronger exception-safety.