Consider this function:
Thing func(){
return something;
}
Every call to this function, a copy of something
is made and passed to the caller.
My question is, why not just do this (every time I want to return something by value)?
const Thing& func(){
return something;
}
This way, we're not risking copying something
without a reason to do so. If the client only needs to 'read' from something
, but not 'write' to it, a const reference can do exactly that. And if the client does need a copy, it can simply assign the const reference to a variable, e.g.:
Thing thing = func(); // the object is passed by const reference, and then copied.
So is there ever a reason to simply return by value?
By the way, it's not that I care so much about optimization, it's just that I don't see a reason to ever return simply by value.
Follow up question: reading the answers, I understand that there are pros and cons for each method. Is there a default? E.g. "default to returning by value"? Or is it purely based on the specific case?