What are the use cases for having a function return by const value for non-builtin type?

Graeme picture Graeme · Jun 10, 2011 · Viewed 9.7k times · Source

Recently I have read that it makes sense when returning by value from a function to qualify the return type const for non-builtin types, e.g.:

const Result operation() {
    //..do something..
    return Result(..);
}

I am struggling to understand the benefits of this, once the object has been returned surely it's the callers choice to decide if the returned object should be const?

Answer

Puppy picture Puppy · Jun 10, 2011

Basically, there's a slight language problem here.

std::string func() {
    return "hai";
}

func().push_back('c'); // Perfectly valid, yet non-sensical

Returning const rvalues is an attempt to prevent such behaviour. However, in reality, it does way more harm than good, because now that rvalue references are here, you're just going to prevent move semantics, which sucks, and the above behaviour will probably be prevented by the judicious use of rvalue and lvalue *this overloading. Plus, you'd have to be a bit of a moron to do this anyway.