If a functions return an int, can an int be assigned to it?

走远了吗. 提交于 2019-11-27 02:04:15

问题


If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function.

int f() {}

f() = 1;

I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules?

int& f() {}

f() = 1;

回答1:


The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it.

int a = 4, b = 5;

int& f() {return a;}

...
f() = 6;
// a is 6 now

Note: you don't assign a value to the function, you just assign to its return value. Be careful with the following:

int& f() { int a = 4; return a; }

You're returning a reference to a temporary, which is no longer valid after the function returns. Accessing the reference invokes undefined behaviour.




回答2:


  • What are Lvalues and Rvalues? by Danny Kalev
  • Lvalues and Rvalues by Dan Saks
  • Lvalues and Rvalues by Mikael Kilpeläinen



回答3:


It's not limit to int only, but for the primitive types there no point in doing it. It's useful when you have your classes




回答4:


If a function returns an object by value, then assignment is possible, even though the function call is an rvalue. For example:

std::string("hello") = "world";

This creates a temporary string object, mutates it, and then immediately destroys it. A more practical example is:

some_function(++list.begin());

You could not write list.begin() + 1, because addition is not possible on list iterators, but increment is fine. This example does not involve assignment, but assignment is just a special case of the more general rule "member functions can be called on rvalues".



来源:https://stackoverflow.com/questions/2216889/if-a-functions-return-an-int-can-an-int-be-assigned-to-it

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