In C++, should my method return an object or a pointer to an object?
How to decide?
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.
What if it's an operator? How can I define?
Many operators such as operator=
normally return a reference to *this
X& X::operator=(X rhs);
You 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:
std::string getstring(){
std::string foo("hello");
foo+=" world";
return foo;
}
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.
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?
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 a unique_ptr
to avoid the copy.
typedef std::array<int,15> MyArray;
std::unique_ptr<MyArray> getArray(){
std::unique_ptr<MyArray> someArrayObj(new MyArray());
someArrayObj->at(3)=5;
return someArrayObj;
}
int main(){
auto x=getArray();
std::cout << x->at(3) <<std::endl; // or since we know the index is right: (*x)[3]
}
Now, to avoid ever writing new
anymore (except for experts in rare cases) you should use a helper function called make_unique
. That will vastly help exception safety, and is as convenient:
std::unique_ptr<MyArray> getArray(){
auto someArrayObj=make_unique<MyArray>();
someArrayObj->at(3)=5;
return someArrayObj;
}
For more motivation and the (really short) implementation of make_unique
, have a look here:
make_unique and perfect forwarding
Update
Now make_unique
is 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