In C++, should my method return an object or a pointer to an object? How to decide? What if it’s an operator? How can I define?
And one more thing – if the pointer turns to be a vector, how can I find out its size after returned? And if it’s impossible, as I think it is, how should I proceed to correctly return an array without this limitation?
Since C++11 we have move semantics in C++ which means that it as easy as before and now also fast to return by value. That should be the default.
Many operators such as
operator=normally return a reference to*thisYou need to look that up for each operator if you would like to comply with the usual patterns (and you should). Start here: Operator overloading
As pointed out by Ed S. return value optimization also applies (even before C++11) meaning that often object you return need neither be copied or moved.
So, this is now the way to return stuff:
The fact that I made a foo object here is not my point, even if you did just do
return "hello world";this is the way to go.The same goes for all copyable or movable types in the standard (these are almost all types, for example
vectors,sets, and what not), except a few exceptions. For example std::arrays do not gain from moving. They take time proportional to the amount of elements. There you could return it in aunique_ptrto avoid the copy.Now, to avoid ever writing
newanymore (except for experts in rare cases) you should use a helper function calledmake_unique. That will vastly help exception safety, and is as convenient:For more motivation and the (really short) implementation of
make_unique, have a look here:make_unique and perfect forwarding
Update
Now
make_uniqueis part of the C++14 standard. If you don’t have it, you can find and use the whole implementation from the proposal by S.T.L.:Ideone example on how to do that