Creating shared_ptr from raw pointer

You need to make sure you don’t initialize both shared_ptr objects with the same raw pointer, or it will be deleted twice. A better (but still bad) way to do it:

classA* raw_ptr = new classA;
shared_ptr<classA> my_ptr(raw_ptr);

// or shared_ptr<classA> my_ptr = raw_ptr;

// ...

shared_ptr<classA> other_ptr(my_ptr);
// or shared_ptr<classA> other_ptr = my_ptr;
// WRONG: shared_ptr<classA> other_ptr(raw_ptr);
// ALSO WRONG: shared_ptr<classA> other_ptr = raw_ptr;

WARNING: the above code shows bad practice! raw_ptr simply should not exist as a variable. If you directly initialize your smart pointers with the result of new, you reduce your risk of accidentally initializing other smart pointers incorrectly. What you should do is:

shared_ptr<classA> my_ptr(new classA);

shared_ptr<classA> other_ptr(my_ptr);

What’s nice is that the code is more concise as well.

EDIT

I should probably elaborate on how it would work with a map. If you had a raw pointer and two maps, you could do something similar to what I showed above.

unordered_map<string, shared_ptr<classA> > my_map;
unordered_map<string, shared_ptr<classA> > that_guys_map;

shared_ptr<classA> my_ptr(new classA);

my_map.insert(make_pair("oi", my_ptr));
that_guys_map.insert(make_pair("oi", my_ptr));
// or my_map["oi"].reset(my_ptr);
// or my_map["oi"] = my_ptr;
// so many choices!

Leave a Comment