Reputation: 765
What is the best way of returning a pointer from a factory ? Should it be a std::unique_ptr
or std::shared_ptr
or just a raw pointer?
Also, I was told, that, one should go for std::unique_ptr
if there is containment and std::shared_ptr
if there is aggregation. Is this the correct way ?
Upvotes: 4
Views: 1241
Reputation: 109169
You should be considering raw pointers only in very special cases, such as passing the pointer across a DLL boundary.
Between shared_ptr
and unique_ptr
, my opinion is to prefer the latter. This leaves the interface more flexible for your users. They can always convert the returned unique_ptr
to a shared_ptr
if they desire to, but more importantly, they can also call unique_ptr::release
and then manually manage the pointer (maybe not a good idea, but it leaves the option open).
If your factory needs to assign a custom deleter for the returned unique_ptr
, a difference in behavior between unique_ptr
and shared_ptr
you should be aware of is that the former will not call the deleter if the managed pointer is nullptr
, but the latter will. So, if your factory may return nullptr
(maybe as a failure condition), and someone converts the unique_ptr
to a shared_ptr
, then make sure the deleter can handle being called with nullptr
as its argument.
Upvotes: 5
Reputation: 6678
You certainly shouldn't return a raw pointer. I think std::unique_ptr and std::shared_ptr are equally fine in most cases. But of course the standard smart pointer classes aren't the only ones. For example, there are classes that implement intrusive reference-counting, and people implement a special smart pointer class to handle them, typically called RefPtr. There are also COM interfaces, for which there is CComPtr.
Upvotes: 0