const attribute makes whole element const?
Jonathan M Davis
jmdavisProg at gmx.com
Sun Sep 9 16:55:03 PDT 2012
On Sunday, September 09, 2012 17:09:23 Namespace wrote:
> On Saturday, 8 September 2012 at 23:18:14 UTC, Timon Gehr wrote:
> > On 09/09/2012 01:16 AM, Namespace wrote:
> >> Why fail this code?
> >> without "const" on "Name" it works fine.
> >>
> >> http://dpaste.dzfl.pl/9fa0986a
> >
> > const fields cannot be written to. This includes the case when
> > the
> > entire struct is written to at once.
>
> But i assign the const attribute in the ctor. So this behaviour
> doesn't make any sense...
const member variables can be initialized but never assigned to. They're
either directly initialized or initialized by the constructor. After that
(including later in the constructor), you can't change them. This also makes
the default assignment operator illegal. You could overload it, and as long as
it doesn't touch any of the const member variables, it would work, but the
const member variable is stuck as it is, and anything trying to mutate is
illegal.
Really, having const member variables is a _bad_ idea IMHO - particularly for
structs. At least with a class, if you try and replace the object's value, you
generally just allocate a new object and assign it to the reference. But with
structs, which are almost always on the stack, you can't assign to it anymore
once it has a const member variable, which causes all kinds of annoying
problems. You're just better off if you never declare structs with const or
immutable member variables.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list