我不清楚返回 const
值对 C++11 中 move 语义的影响。
这两个返回数据成员的函数有什么区别吗? const
在 C++11 中仍然是多余的吗?
int GetValueA() { return mValueA; }
const int GetValueB() { return mValueB; }
这些功能呢?
int GetValuesAB() { return mValueA + mValueB; }
const int GetValuesCD() { return mValueC + mValueD; }
最佳答案
调用按值返回的函数的表达式是纯右值。但是,没有非类非数组类型的 const
纯右值 (§5/6):
If a prvalue initially has the type “cv
T
,” whereT
is a cv-unqualified non-class, non-array type, the type of the expression is adjusted toT
prior to any further analysis.
这意味着您对函数的两个定义之间没有区别。它返回 const int
还是仅返回 int
是无关紧要的,因为表达式永远不会是 const
。
但是,返回类类型时会有所不同。考虑以下示例:
struct foo
{
void bar() { std::cout << "Hello" << std::endl; }
};
foo get_foo();
现在,如果我们调用 get_foo()
,我们会得到一个临时的 foo
对象。这个纯右值不是const
,我们可以在它上面调用非const
成员函数,所以我们可以愉快地做get_foo().bar()
.但是,我们可以像这样更改 get_foo
的声明:
const foo get_foo();
现在,表达式 get_foo()
是一个 const
纯右值(这是允许的,因为它是一个类类型),我们不能调用 bar
在它返回的临时对象上。
尽管如此,谈论非类类型的 move 语义是没有意义的,因为 int
永远不会被 move 。如果您返回一个 const
类类型,也不能从中 move ,因为它是 const
。演示:
foo get_foo();
foo f(get_foo()); // Will call the move constructor
const foo get_foo();
foo f(get_foo()); // Will call the copy constructor
这是因为 const
纯右值不会绑定(bind)到非 const
右值引用, move 构造函数将其作为参数。
关于c++ - C++11 中返回 const 值类型对 move 语义的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15745359/