C++: is return value a L-value?

你说的曾经没有我的故事 提交于 2019-11-27 05:13:09

问题


Consider this code:

struct foo
{
  int a;
};

foo q() { foo f; f.a =4; return f;}

int main()
{
  foo i;
  i.a = 5;
  q() = i;
}

No compiler complains about it, even Clang. Why q() = ... line is correct?


回答1:


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)

If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1)

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.

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.




回答2:


Because structs can be assigned to, and your q() returns a copy of struct foo so its assigning the returned struct to the value provided.

This doesn't really do anything in this case thought because the struct falls out of scope afterwards and you don't keep a reference to it in the first place so you couldn't do anything with it anyway (in this specific code).

This makes more sense (though still not really a "best practice")

struct foo
{
  int a;
};

foo* q() { foo *f = new malloc(sizeof(foo)); f->a = 4; return f; }

int main()
{
  foo i;
  i.a = 5;

  //sets the contents of the newly created foo
  //to the contents of your i variable
  (*(q())) = i;
}



回答3:


One interesting application of this:

void f(const std::string& x);
std::string g() { return "<tag>"; }

...

f(g() += "</tag>");

Here, g() += modifies the temporary, which may be faster that creating an additional temporary with + because the heap allocated for g()'s return value may already have enough spare capacity to accommodate </tag>.

See it run at ideone.com with GCC / C++11.

Now, which computing novice said something about optimisations and evil...? ;-].



来源:https://stackoverflow.com/questions/6111905/c-is-return-value-a-l-value

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