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

风格不统一 提交于 2019-11-26 20:06:15

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.

It is occasionally useful. See this example:

class I
{
public:
    I(int i)                   : value(i) {}
    void set(int i)            { value = i; }
    I operator+(const I& rhs)  { return I(value + rhs.value); }
    I& operator=(const I& rhs) { value = rhs.value; return *this; }

private:
    int value;
};

int main()
{
    I a(2), b(3);
    (a + b) = 2; // ???
    return 0;
}

Note that the value returned by operator+ would normally be considered a temporary. But it's clearly being modified. That's not exactly desired.

If you declare the return type of operator+ as const I, this will fail to compile.

There is no benefit when returning by value. It doesn't make sense.

The only difference is that it prevents people from using it as an lvalue:

class Foo
{
    void bar();
};

const Foo foo();

int main()
{
    foo().bar(); // Invalid
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!