Pass 'this' as reference

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Sep 15 20:13:51 UTC 2018


On Saturday, September 15, 2018 11:44:05 AM MDT Jan via Digitalmars-d-learn 
wrote:
> On Thursday, 13 September 2018 at 11:08:30 UTC, Jonathan M Davis
>
> wrote:
> > [...]
>
> Thanks for clarifying Jonathan :)
> But aren't the variables considered rvalues then?

No. variables are _always_ lvalues. An lvalue is an object which is
addressable and which can therefore be assigned a value (ignoring issues of
constness). The name comes from the fact that lvalues are allowed on the
left-hand side of an assignment operation, whereas rvalues are only allowed
on the right. e.g.

int i;
int* p;

are both lvalues. They have addresses and can be assigned to.

i = 42;
p = &i;
auto p2 = &p;

On the other hand, the return value of

int foo(string s);

is an rvalue. How it's actually stored is compiler-defined; you can't take
its address, and you can't assign to it.

foo("bar") = 42; // illegal
auto p = &foo("bar"); // illegal

On the other hand,

ref int foo(string s);

returns by ref, so it's returning an lvalue. Its address can be taken, and
it can be assigned a value.

foo("bar") = 42; // legal
auto p = &foo("bar"); // legal

Because a pointer or reference points to a specific address, even if the
pointer itself is an rvalue, what it points to is almost always an lvalue,
(the main case where it isn't an lvalue would be something like a function
pointer, since you can take a function's address, but you can't assign to
it). So, something like

int* foo(string s);
*foo("bar") = 42;

compiles. However, ultimately, you can't know whether a particular value is
an lvalue or rvalue without context. A variable is always an lvalue, whereas
a return value usually isn't - but it can be if it's returned by ref. And a
variable and return value could both be the same type - int, int*, string,
etc. So, the type itself doesn't tell you whether something is an lvalue or
rvalue. It's how it's stored that tells you.

Ultimately though, if you want to know whether something is an lvalue or
rvalue, consider whether it's something that can go on the left-hand side of
an assignment operation (ignoring its constness), or whether it can only go
on the right-hand side.

https://msdn.microsoft.com/en-us/library/f90831hc.aspx
https://stackoverflow.com/questions/17357888/exact-difference-between-rvalue-and-lvalue
https://www.quora.com/What-is-lvalue-and-rvalue-in-C

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list