The point of const, scope, and other attributes

Ali Çehreli acehreli at yahoo.com
Sat May 14 01:11:03 UTC 2022


On 5/13/22 17:04, Tejas wrote:
 > On Friday, 13 May 2022 at 18:43:11 UTC, H. S. Teoh wrote:
 >> On Fri, May 13, 2022 at 06:25:22PM +0000, Fry via Digitalmars-d wrote:
 >>> > > [...]
 >> [...]
 >>> [...]
 >>
 >> Yeah, more than one long-time D user (including myself) has come to
 >> this conclusion. In my own experience, const is mainly useful at the
 >> lowest levels of code (strings, leaf-node modules that operate on some
 >> self-contained data structure that doesn't depend on anything else).
 >> Once you get to a high enough level of abstraction, it starts getting
 >> in your way and becomes far too much more work than the benefits it
 >> offers; it's just not worth the trouble.  So these days I don't really
 >> bother with const, except in small pockets of leaf-node code.
 >>
 >>
 >>> [...]
 >> [...]
 >>
 >> I thought `auto ref` was supposed to do this?  But I recall people
 >> hating `auto ref` for various reasons...
 >>
 >>
 >> T
 >
 > Both `auto ref` and `in` make a copy if it's an rvalue.

'in' may not copy rvalues when compiled with -preview=in:

import std.stdio;

struct S(size_t N) {
   int[N] i; // Can be veeery big

   this (int i) {
     writeln("When constructing: ", &this.i);
   }
}

void foo(T)(in T s) {
   writeln("Inside foo       : ", &s.i);
}

void main() {
   foo(S!1(42));
   foo(S!1000(43));
}

foo() receives two rvalue objects, second of which is passed by 
reference just because the compiler decided to do so:

When constructing: 7FFD44B79EA0
Inside foo       : 7FFD44B79E78  // <-- Copied for N==1; who cares. :)
When constructing: 7FFD44B79EB0
Inside foo       : 7FFD44B79EB0  // <-- rvalue passed by reference.

That prooves D does indeed support rvalue references. :D

 > Idk why people hate `auto ref` though... most likely the fact that one
 > might have to do `__traits(isRef, symbol)` anyways for some edge cases

My discomfort with 'auto ref' is, it comes with a guideline: Treat the 
parameter 'const'. If not, an rvalue object would be mutated but the 
outside world would not know about it (mostly). Why would it be 
different for lvalues? Because they are passed by reference, the caller 
has an interest in the mutation, right?

So, I can't imagine a use case where lvalue mutation is important but 
rvalue mutation is not.

Ali



More information about the Digitalmars-d mailing list