digitalmars.D.learn - Wrong const attribute?
- Paolo Invernizzi (22/22) Sep 22 2011 charset=us-ascii
- travert phare.normalesup.org (Christophe) (11/41) Sep 23 2011 Since your Bar has am immutable member, you cannot assign a Bar
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
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