Return pointer from factory

What is the best way to return a pointer from a factory? Should it be std::unique_ptr or std::shared_ptr or just a raw pointer?

In addition, I was told that you need to go std::unique_ptr if there is containment and std::shared_ptr if there is aggregation. Is it correct?

+4
source share
2 answers

You should only consider source pointers in special cases, such as passing a pointer across a DLL boundary.

Between shared_ptr and unique_ptr , my opinion should prefer the latter. This makes the interface more flexible for your users. They can always convert the returned unique_ptr to shared_ptr if they wish, but more importantly, they can also call unique_ptr::release and then manually manipulate the pointer (maybe this is not a good idea, but it leaves the option open).

If your factory needs to assign a custom delete element for the unique_ptr returned, the difference in behavior between unique_ptr and shared_ptr that 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 can return nullptr (possibly as a failure condition), and someone converts unique_ptr to shared_ptr , then make sure that the remote statement can handle the call with nullptr as an argument.

+5
source

You, of course, should not return a raw pointer. I think std :: unique_ptr and std :: shared_ptr are equally good in most cases. But, of course, the standard classes of smart pointers are not the only ones. For example, there are classes that implement intrusive reference counting, and people implement a special class of smart pointers to handle them, usually called RefPtr. There are also COM interfaces for which CComPtr is available.

0
source

Source: https://habr.com/ru/post/1441973/


All Articles