Why is it possible to call non-const member functions of rvalues but a compile error to modify members or rvalues directly?

Johannes Loher johannes.loher at fg4f.de
Sat Jun 13 11:26:58 UTC 2020


Consider the following example:

```
struct A
{

    auto a(int _a)
    {
        return this._a = _a;
    }

    int _a = 0;
}

void main()
{
    static assert(!__traits(compiles, { A()._a = 2; }));
    static assert(__traits(compiles, { A().a(2); }));
}
```
(https://run.dlang.io/is/GkmpA8)

Why is it a compile error to set `_a` directly but calling `a` just
works fine?

If we prevent modifying members of rvalues directly, I would also expect
calling non-const member functions of rvalues to be prevented.


More information about the Digitalmars-d-learn mailing list