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 ?
You should be considering raw pointers only in very special cases, such as passing the pointer across a DLL boundary.
Between
shared_ptrandunique_ptr, my opinion is to prefer the latter. This leaves the interface more flexible for your users. They can always convert the returnedunique_ptrto ashared_ptrif they desire to, but more importantly, they can also callunique_ptr::releaseand 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 betweenunique_ptrandshared_ptryou should be aware of is that the former will not call the deleter if the managed pointer isnullptr, but the latter will. So, if your factory may returnnullptr(maybe as a failure condition), and someone converts theunique_ptrto ashared_ptr, then make sure the deleter can handle being called withnullptras its argument.