dmd 2.063 beta 5
Steven Schveighoffer
schveiguy at yahoo.com
Thu May 23 07:02:56 PDT 2013
On Thu, 23 May 2013 09:50:28 -0400, Artur Skawina <art.08.09 at gmail.com>
wrote:
> On 05/23/13 15:12, Don wrote:
>> On Thursday, 23 May 2013 at 11:08:16 UTC, Artur Skawina wrote:
>>> struct Packet(uint TYPE) {
>>> immutable uint type = TYPE;
>>> // ...
>>> }
>>
>> But that allows you to write:
>>
>> auto w = Packet!(7)(6);
>>
>> which sets type to 6 !
>
> No, it doesn't - this is why the "const and initialized, but still
> mutable" class
> is a bad idea. Modifying already initialized immutable data needs to be
> forbidden.
There is a misconception here. The data is not fully initialized when the
ctor is called, it's just that the memory where the instance lives happens
to have a bit pattern in it with the value 7 when the ctor gets it.
It's no different than a non-default initialized immutable being
"initialized" to 0 first before you set it. It's just you get to define
the bit pattern instead of using 0.
In order to disable the behavior above, you have to disable the default
ctor, define a non-default ctor, or generate using a static
method/function.
-Steve
More information about the Digitalmars-d-announce
mailing list