cannot modify struct with immutable members

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 2 19:12:52 PST 2015


On Sat, 03 Jan 2015 13:25:31 +1030
ted via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> 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.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150103/bc773587/attachment.sig>


More information about the Digitalmars-d-learn mailing list