I think I might need to do something like the following pseudo-code in my application:
boost::shared_ptr<T> p;
...
...
p = boost::shared_ptr<T>(new T);
I realize there are other options for using the assignment operator, but I noticed in the boost::shared_ptr documentation/example that they never discussed a case like this one involving the default constructor.
My question I suppose, is: is this valid use? In other words, is it legal and could it lead to potential memory leaks? Appreciate any ideas/corrections. Thanks much!
NOTE: I do recall reading, as also some comments below suggest, that they recommend to always use a named shared_ptr when invoking the constructor with new. Still, I find it hard to imagine this might cause any harm. Kindly post any counter-examples if you have them. Thanks!
It is perfectly legal and memory safe. The fact that you are invoking the default constructor on
Tis irrelevant: as long as you have a dynamically allocated object, you can wrap it in ashared_ptr<>If you refer to the default constructor of
shared_ptr<>that’s fine too: the wrapped pointer is NULL, which will not be deleted when the othershared_ptr<>is assignedYou will have to be careful, though to check whether the contents are NULL or not, otherwise you might be accessing an invalid pointer