What kind of smart pointer to return?

Hello
This is a dilemma i run in to quite often and i figured i would finally ask about it.
I have a function and i want to return an object to the user. What exactly should i return?

First of all i should probably return a pointer rather than trying to copy or move the object because that is slower (right?).

But the problem then is: what kind of pointer should i return? a unique pointer? what if the user intends to share the pointer and so he now needs to spend resources on converting it.

And vice versa if i return a shared_ptr but the user actually isn't sharing it then it would be a waste of resources to have created a shared_ptr in the first place.

I also thought about just returning the raw pointer and then letting the user create whichever kind of smart pointer he wants from it like this:
 
std::unique_ptr<T> myPtr{ MyFunc() };


But then i read here (https://stackoverflow.com/questions/20895648/difference-in-make-shared-and-normal-shared-ptr-in-c) that this way of initializing smart pointers can have disadvantages.

So what should i do?
Last edited on
slav wrote:
First of all i should probably return a pointer rather than trying to copy or move the object because that is slower (right?).

Nope.

RVO typically avoids all those kinds of problems. So the answer is:

Don’t use pointers at all.

Only use pointers when you have no other choice. And when you do, prefer a std::unique_ptr over a std::shared_ptr.

Hope this helps.
Topic archived. No new replies allowed.