Confused about const

biozic dransic at free.fr
Fri Mar 19 19:15:48 PDT 2010


My guess is that:

> struct S {
>   int x;
>   int[] a;
> }
>
> S foo(const S b) {

foo makes the promise that b's members won't change: so 'b.x' is 
implicitely const(int) and 'b.a' is implicitely const(int[]).

>      S other = b;

Here you assign 'b.x', which is const(int), to 'other.x', which is int. 
You can assign an const(int) to an int: after the value is copied, 
changing 'other.x' won't change 'b.x'.
But then you assign 'b.a', which is const(int[]), to 'other.a' which is 
int[]. This is forbidden: this would copy the reference to the array 
from 'b' to 'other', and after the copy, you would be able to change the 
content of 'b.a' by changing the content of 'other.a', thus going 
against const.

I'm not sure if this is completely right nor if I'm completely clear, 
though... :)

Nicolas


More information about the Digitalmars-d-learn mailing list