`const ref T` or `ref const T`?

IchorDev zxinsworld at gmail.com
Thu Aug 15 09:05:02 UTC 2024


On Thursday, 15 August 2024 at 00:35:33 UTC, Manu wrote:
> The reason I perceive is that this is valid syntax: auto ref
> const(CowArray) rhs
> This is not: const(auto ref CowArray) nhs
>
> For me, it's a conceptual flow thing:
> const auto ref T goes: type stuff (const) -> storage class 
> stuff (auto ref)
> -> type stuff (T)
> auto ref const T goes: storage class stuff (auto ref) -> type 
> stuff (const T
> )
>
> It feels crude to interleave type stuff and storage class stuff 
> in an arbitrary way.
>
> The distinction feels more compelling when you consider that 
> parens may appear after type constructors (const(T)), and so in 
> those cases, the code MUST be written with the const 
> immediately preceding the type, forcing the storage class to 
> the left.
>
> Since it's invalid to put storage class stuff on the end 
> (actual type must be on the end), then I would mandate that 
> storage class stuff should go at the start, not randomly in the 
> middle somewhere, ie: storage_class type_constructor actual_type
>
> If it were up to me, I would mandate this in the spec, but 
> failing that, at least proliferate this by general policy; I 
> think this helps non-D coders to osmose this complexity without 
> a detailed conversation... and for everyone else, the code just 
> reads more consistently.
>
> I see a surprising number of people writing `const ref T`, and 
> I suspect that people are writing it holding the same kind of 
> conceptual confusion that a lot of new users have expressed to 
> me. As I see it, the fact people tend to write this at all is 
> clear evidence that we shouldn't allow it!

Yeah, I feel you. When I first started writing in D I’d also use 
`const ref`, but I agree that interleaving the storage class and 
the type is not right. I’m not alone in having started with 
`const ref`, and then having moved to using `ref const` as I 
understood the language better.
I think part of the reason some gravitate to `const ref` because 
of ignorance when coming from C++, but I never used C++ because I 
was aware of its reputation. Instead, I found the ordering to 
violate English adjective ordering. `ref const T` sounds wrong in 
the same way as ‘red big balloon’. In English you can have a 
‘constant reference integer’ but not a ‘reference constant 
integer’; it sounds like an imperative instruction.


More information about the Digitalmars-d mailing list