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

牧云@^-^@ 提交于 2019-11-28 07:46:47
Alexander Gessler

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.

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

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".

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