On Sat, 03 Jan 2015 13:25:31 +1030 ted via Digitalmars-d-learn <[email protected]> wrote:
>
> I get the following error from the code below: (dmd2.066.1, linux)
> test.d(26): Error: cannot modify struct myTest1 Test with immutable members
>
> Is this expected?
>
> If so, how can I achieve this result - being able to set (a new) initial
> value
> of myTest1 from within an nested function ?
>
> thanks !
> ted
>
>
> code:
> struct A
> {
> int someInt;
> }
>
> struct Test
> {
> this( ref const(A) arg )
> {
> mA = arg;
> }
>
> private:
> const(A) mA;
> }
>
> void main()
> {
> Test myTest1;
> A topA;
>
> void _someFunc( ref const(A) myA )
> {
> myTest1 = Test(myA);
> }
>
> Test myTest2 = Test(topA); // is ok as expected
> _someFunc( topA ); // error.
> }
the question is: "why do you want `mA` to be const?" leaving aside
compiler complaints this is the one and important question. let's try
to fix your code instead of devising workarounds to beat the
compiler. ;-)
please remember that D `const` is not the same as C/C++ `const`, so my
question is not so stupid as it may look.
p.s. you can use `in A myA` instead of `ref const A myA`, in most cases
compiler is intelligent enough to use "pass-by-reference" for `in` args.
signature.asc
Description: PGP signature
