const and immutable values, D vs C++?

Bastiaan Veelo Bastiaan at
Wed Dec 4 22:43:35 UTC 2019

On Wednesday, 4 December 2019 at 14:44:43 UTC, Ola Fosheim 
Grøstad wrote:
> When is there a noticable difference when using const values 
> instead of immutable values in a function body? And when should 
> immutable be used instead of const?
> f(){
>   const x = g();
>   immutable y = g();
>   ... do stuff with x and y …
> }

There is a difference I guess if g() returns a reference type and 
is an inout function. immutable y will only work if the reference 
returned is immutable.

Const is a promise to the rest of the code that you will never 
mutate it. Immutable is a promise by the rest of the code that it 
will never mutate.

Immutable is more powerful, allowing data sharing in overlapping 
slices and between threads without locks. Const is more 
versatile, allowing references to data regardless of its 

So if g() always returns immutable, it’s best to receive it as 
such, not const. If it can be either, it must be received as 

> I'm comparing D to C++ and I get the following mapping:

Does that make sense at all? D’s const is transitive, C++’s is 


More information about the Digitalmars-d-learn mailing list