www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Initializing structure that is a member of a const structure

reply "Maksim Zholudev" <maximzms gmail.com> writes:
Trying to make my program care about const qualifier I've ended 
up with the following problem:
-----------------
struct Foo
{
     int* a;

     inout this(inout int* src) pure
     {
         a = src;
     }

     inout void opAssign(inout Foo f) pure
     {
         a = f.a; // Error: can only initialize const member a 
inside constructor
     }
}

struct Boo
{
     Foo foo;

     inout this(inout int* src) pure
     {
         foo = Foo(src);
     }
}
-----------------
This code would work even without opAssign but let's imagine we 
need it for some reason.
Is there any way to initialize `foo` without opAssign call?
Mar 03 2013
parent reply "Maxim Fomin" <maxim maxim-fomin.ru> writes:
On Sunday, 3 March 2013 at 18:36:47 UTC, Maksim Zholudev wrote:
 Trying to make my program care about const qualifier I've ended 
 up with the following problem:
D's type system is not a right thing to care about. Note, that the purpose of inout is to transmit qualifier from parameter to return type. Inout in constructors and void functions doesn't make much sense. And your code does not demonstrate necessity to make any of parameters as inout.
 This code would work even without opAssign but let's imagine we 
 need it for some reason.
 Is there any way to initialize `foo` without opAssign call?
Yes, const cast. The real answer is "no", because qualifiers do not work well with special functions(operator overloads, constructors, destructors, postblits).
Mar 03 2013
parent "Maksim Zholudev" <maximzms gmail.com> writes:
Thank you.
Mar 04 2013