www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Wrong const attribute?

reply Paolo Invernizzi <arathorn fastwebnet.it> writes:
	charset=us-ascii

Hi all,=20

I've found nothing on bugzilla for that, what I'm missing? Or it's a =
bug? (DMD 2.055)

struct Bar {
    immutable int i;
    this(int j){ i =3D j; }
}

struct Foo {
    Bar bar;
}

void main(){
   =20
    auto b =3D Bar(1);
   =20
    auto f =3D Foo();
    f.bar =3D Bar(2); // Error: can only initialize const member bar =
inside constructor
   =20
}

Cheers,=20
Paolo Invernizzi
Sep 22 2011
parent travert phare.normalesup.org (Christophe) writes:
Paolo Invernizzi , dans le message (digitalmars.D.learn:29680), a
 écrit :
 
 --Apple-Mail-7--919646864
 Content-Transfer-Encoding: quoted-printable
 Content-Type: text/plain;
 	charset=us-ascii
 
 Hi all,=20
 
 I've found nothing on bugzilla for that, what I'm missing? Or it's a =
 bug? (DMD 2.055)
 
 struct Bar {
     immutable int i;
     this(int j){ i =3D j; }
 }
 
 struct Foo {
     Bar bar;
 }
 
 void main(){
    =20
     auto b =3D Bar(1);
    =20
     auto f =3D Foo();
     f.bar =3D Bar(2); // Error: can only initialize const member bar =
 inside constructor
    =20
 }
 
Since your Bar has am immutable member, you cannot assign a Bar instance, which is what you do in the line where there is an error. If you want to perform an assignment, Bar.i cannot be immutable. If you really want Bar.i to be immutable, Foo must hold a pointer to Bar, so you can change this pointer, or Bar can be a class instead of a struct (which means Foo does contain a pointer to Bar, but you don't have to notice it). -- Christophe Travert
Sep 23 2011