function returning an int cannot be assigned to

I have a confusion. A function returning a value of type int cannot be assigned to - is it because that return value is an rvalue? but its type is int not int&& ??


1
2
3
4
5
6
7
struct A { int i = 0; int& value() { return i; } };
struct B { int i = 0; int value() { return i; } };

A a;
a.value() = 20;    // OK a.value() is an lvalue (a reference to an int i.e.int&)
B b;
b.value() = 20;    //  NOT OK b.value() returns an int (not addressable temporary) 


Last edited on
My question is why one would want to do this?

Variable i is public.

One could write 2 versions of operator()() ; First takes no arguments and returns the value; second one takes an int argument and sets variable i with it.

Which standard of C++ are you compiling against? C++17 has RVO.

b.value() returns an int (not addressable temporary)


Correct. The return for b is a temp value - not a ref. You are trying to change the value of a temp which isn't allowed. A return of && is an rvalue ref.

This article may be of interest:
https://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html

Like returning a ref, with returning && you have to be careful re the scope of what is returned.

Last edited on
Topic archived. No new replies allowed.