const in functions

Salih Dincer salihdb at hotmail.com
Sat Mar 18 14:34:10 UTC 2023


On Friday, 17 March 2023 at 22:41:18 UTC, Ali Çehreli wrote:

> My comment was purely technical. What I meant is, if the code 
> is an island where there is no single 'const' in sight, then a 
> D programmer can live by ignoring 'const'. At a technical 
> level...
>
> This is different from C++ where you have to use references to 
> const in order to take rvalue references as parameters. Since D 
> does not allow binding rvalues even to references to const, 
> this is a moot point. (-preview=in does bind rvalues to 
> references as an optimization but that fact is hidden from the 
> programmer.)

Let's increase the level one bit...

Again we will remain within the boundaries of `-preview=in`, but 
we will learn other hidden information. Because you get 
interesting results when you raise the issue to function 
overloading. Here's what happens when you compile the following 
example:

https://wandbox.org/permlink/XvInUjEtMKOS0CVD

1. I guess none of objects are created copy.  Because Apple has 
already `ref` and Pineapple didn't execute ctor because of `in` 
keyword.  Isn't Quince also a `const` but it was created when it 
is not a copyible object:

> ref: Apple
> in: Pinapple
> const: Quince
> 0 copies... [Apple: paid, pinapple, quince]

2. If there is no function that takes `ref`, Apple prefers 
`const`. Please just hide the function under the version block. 
In this case, ctor will run once:

> const: Apple
> in: Pinapple
> const: Quince
> 1 copies... [qpple, pinapple, quince]

3. If you replace `in` with `scope` (function 3) then pineapple 
and quince will also select different functions:

> const: Apple
> const: Pinapple
> in: Quince
> 2 copies... [qpple, qinapple, puince]

With this example, it is possible to obtain dozens of results 
like these. I love D, D is a very powerful language.

SDB at 79


More information about the Digitalmars-d-learn mailing list