cannot modify struct with immutable members
ted via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 2 20:15:24 PST 2015
Well, I just cleared up some of my misunderstanding.
I did not realise the mA (within struct Test) would be a _copy_ of arg, not
a reference (pointer) to arg.
So the more correct code snippet would be:
struct A
{
int someInt;
}
struct Test
{
@property { const(A) getA() { return *mA; } }
this( in A arg )
{
mA = &arg;
}
private:
const A* mA;
}
void main()
{
Test myTest1;
A topA;
topA.someInt = 100;
void _someFunc( in A myA )
{
myTest1 = Test(myA);
}
Test myTest2 = Test(topA); // is ok as expected
_someFunc( topA );
}
which fails to compile for the same reason (test.d(30): Error: cannot
modify struct myTest1 Test with immutable members)
(I have been able to work around my original issue by removing @safe from
Test, and then cast()ing ... but this is ugly)
This code snippet is me trying to understand whether I have a fundamental
misunderstanding with const, or whether it is an issue with the compiler
(I agree with your view that 'fixing my code' is the correct approach, btw
- I'm still curious).
(The reason for this basic structure is that _someFunc is a callback from
another module, and myTest1 contains state information that is
created/adjusted via the callback. And (to be safe) myTest1 contains
references to other structures that it should not adjust - hence the
const()).
....and I can't use @safe and pointers......
So, it appears I need to do what I want with classes, not structs:
i.e.
import std.stdio;
class A
{
int someInt;
}
@safe class Test
{
@property { const(A) getA() { return mA; } }
this( in A arg )
{
mA = arg;
}
private:
const A mA;
}
void main()
{
Test myTest1;
A topA = new A;
topA.someInt = 100;
void _someFunc( in A myA )
{
myTest1 = new Test(myA);
}
Test myTest2 = new Test(topA); // is ok as expected
_someFunc( topA );
writeln( "topA: ", topA.someInt );
writeln( "myTest1.A: ", myTest1.getA.someInt );
}
I'm happy I've got a workaround (which seems to safely preserve the
const'dness), but I still don't understand why the compiler barfs on the
struct version as it should be 'replacing' the higher scoped variable....
anyway...thanks for your response.....apologies for the streaming
conciousness of this reply.......
More information about the Digitalmars-d-learn
mailing list