How to break const
Matthias Walter
xammy at xammy.homelinux.net
Sun Jun 17 23:14:11 PDT 2012
On 06/18/2012 08:04 AM, Mehrdad wrote:
> On Monday, 18 June 2012 at 06:00:11 UTC, Matthias Walter wrote:
>> On 06/18/2012 07:36 AM, Mehrdad wrote:
>>> Is it just me, or did I subvert the type system here?
>>>
>>>
>>> import std.stdio;
>>>
>>> struct Const
>>> {
>>> this(void delegate() increment)
>>> { this.increment = increment; }
>>> int a;
>>> void delegate() increment;
>>> void oops() const { this.increment(); }
>>> }
>>>
>>> void main()
>>> {
>>> Const c;
>>> c = Const({ c.a++; });
>>> writeln(c.a);
>>> c.oops();
>>> writeln(c.a);
>>> }
>>>
>>
>> I don't think so. When calling oops you have two references to the
>> object c:
>>
>> - The this-pointer of the object itself which is not allowed to change
>> the object in the const-call.
>> - The reference from within main which is allowed to change it and can
>> be reached via the frame pointer of the delegate.
>>
>> I see this as perfectly valid code. Of course, opinions may differ here.
>>
>> Matthias
>
>
>
> My trouble isn't with the delegate, it's with the const method.
>
> It's with the idea that "you can tell something about the code just by
> looking at it".
>
> The way I understood it, you can assume that a `const` method cannot
> modify an object, but... that doesn't seem to be the case here.
>
> What am I misunderstanding?
Its not, that a const method cannot modify an object, it just ensures
that the const method cannot modify the object *by using the this-pointer*.
Other things cannot be ensured with const: For example, a const method
could wake up a 2nd thread and proceed with a longer computation. Then
this 2nd thread may have a reference to the object and may change it
while your computation is going on.
More information about the Digitalmars-d
mailing list