Suppose I have a class Foo
with a std::string
member str
. What should get_str
return?
std::string Foo::ge
In general (unless there's a proven performance issue) I would return by value.
First of all there's a semantic difference, if your property changes do you want your clients to be updated of the change or get the value at the moment of calling the function?
There's the obvious correctness issue, if you return by reference the entity calling the function may hold on to the reference and may use it after your object was destructed (which is not so good).
Another problem is with multiple threaded code, if one thread reads from the const reference while you're updating the variable your in for lots of trouble.
In any case I think the most common use case is when the caller of the function stores the value in a variable.
string val = obj->get_str();
// use val now
If this is true (as opposed to cout << obj->get_str()
where there is no variable) you always have to construct a new string for val
even if you return by reference and since compilers can perform RVO the by-value version will not under-perform the by-const-ref variant.
In conclusion: if you know it's a performance issue and you are sure that the return value will not be stored for longer than your object will exist and you don't expect to be used from different threads, then it's OK to return by const reference.
Generally you should return PODs by value (e.g, int, short, char, long etc,) and a const reference for more complex types:
int getData() const;
short getMoreData() const;
const std::string& getName() const;
const ComplexObject& getComplexData() const;