返回const值以利用移动语义与防止诸如(a + b)= c之类的东西

Jul*_*ian 7 c++ operator-overloading move-semantics c++11

我认为这个问题有点被误解了.

回归const价值并不是可以被视为毫无意义的东西.正如Adam Burry在评论中指出的那样,Scott Meyers在更有效的C++(第6项)中推荐它,我将添加Herb Sutter的Exceptional C++(第20项,类机械,其相应的GotW 可在线获得).

这样做的理由是你希望编译器能够捕获像(a+b)=c(oops,意思==)或误导性语句这样的错别字a++++,这两种语句都被标记为开箱即用的原始类型int.因此,对于喜欢的东西operator+operator++(int),返回const值有一定道理.

另一方面,正如已经指出的那样,返回a会const阻止C++ 11的移动语义,因为它们需要const右值引用.

所以我的问题是,我们真的不能吃蛋糕吗?(我找不到办法.)

Jar*_*d42 10

你可以做什么而不是返回const元素是将方法限制为左值对象:

struct S
{
    S& operator =(const S& rhs) & // note the final &
                                  // to restrict this to be lvalue
    {
        // implementation
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

所以

S operator +(const S& lhs, const S& rhs);
S a, b, c;
Run Code Online (Sandbox Code Playgroud)

以下是非法的:

(a + b) = c;
Run Code Online (Sandbox Code Playgroud)

实例