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

╄→尐↘猪︶ㄣ 提交于 2019-11-26 07:29:15

问题


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?


回答1:


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.




回答2:


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.




回答3:


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
}


来源:https://stackoverflow.com/questions/6299967/what-are-the-use-cases-for-having-a-function-return-by-const-value-for-non-built

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