C ++:是一个L值的返回值? [英] C++: is return value a L-value?
问题描述
请考虑以下代码:
struct foo
{
int a;
};
foo q() { foo f; f.a =4; return f;}
int main()
{
foo i;
i.a = 5;
q() = i;
}
没有编译器抱怨,甚至Clang。为什么 q()= ...
行是正确的?
No compiler complains about it, even Clang. Why q() = ...
line is correct?
推荐答案
不,当且仅当它是一个引用(C ++ 03)时,函数的返回值是一个l值。 (5.2.2 [expr.call] / 10)
No, the return value of a function is an l-value if and only if it is a reference (C++03). (5.2.2 [expr.call] / 10)
如果返回的类型是基本类型,那么这将是一个编译错误。 (5.17 [expr.ass] / 1)
If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1)
这是因为你可以调用成员函数(甚至非 - const
成员函数)对类类型的r值和
foo
的赋值是一个实现定义的成员函数: foo& foo :: operator =(const foo&)
。第5节中对运算符的限制仅适用于内置运算符(5 [expr] / 3),如果重载解析为运算符选择了重载函数调用,则对该函数调用的限制适用
The reason that this works is that you are allowed to call member functions (even non-const
member functions) on r-values of class type and the assignment of foo
is an implementation defined member function: foo& foo::operator=(const foo&)
. The restrictions for operators in clause 5 only apply to built-in operators, (5 [expr] / 3), if overload resolution selects an overloaded function call for an operator then the restrictions for that function call apply instead.
这就是为什么有时候推荐返回类型为 const
对象的对象(例如 const foo q();
),但是这可能对C ++ 0x有负面影响,它可以阻止move语义从他们应该工作。
This is why it is sometimes recommended to return objects of class type as const
objects (e.g. const foo q();
), however this can have a negative impact in C++0x where it can inhibit move semantics from working as they should.
这篇关于C ++:是一个L值的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!