How to break const
deadalnix
deadalnix at gmail.com
Mon Jun 18 05:47:58 PDT 2012
Le 18/06/2012 09:58, Jonathan M Davis a écrit :
> On Monday, June 18, 2012 08:19:55 Mehrdad wrote:
>> On Monday, 18 June 2012 at 06:14:22 UTC, Matthias Walter wrote:
>>> 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*.
>>
>> I see...
>>
>>
>> So that means you /can't/ tell something just by looking at a
>> part of the code, right?
>>
>> (Just mentioning this since this idea seemed to be emphasized a
>> lot by D.)
>
> You can if the function is pure as well, because then that delegate would not
> be legal. For instance, this code
>
> import std.stdio;
>
> struct Const
> {
> this(void delegate() pure increment)
> { this.increment = increment; }
> int a;
> void delegate() pure increment;
> void oops() const pure { this.increment(); }
> }
>
> void main()
> {
> Const c;
> c = Const({ c.a++; });
> writeln(c.a);
> c.oops();
> writeln(c.a);
> }
>
>
> fails to compile, giving this error:
>
> q.d(15): Error: constructor q.Const.this (void delegate() pure increment) is
> not callable using argument types (void delegate() nothrow @safe)
>
> All const guarantees is that the object isn't altered through the const
> reference/pointer (which in the case of a const function is this). That's
> powerful, but it needs pure as well to really be able to just glance at it and
> know that it's not altering your object.
>
> If you want an extreme exampl. you could create an object whose entire state
> was held in a global variable, then the fact that the this pointer was const
> wouldn't mean much. But if the member functions were pure, then you couldn't
> access that global variable, and so that externalization of the state wouldn't
> work, and you'd be guaranteed that the const function didn't alter your object
> (as long as none of the arguments to that const function held a reference or
> pointer to that object anyway (though that's a fairly abnormal thing to do) -
> only strong purity absolutely guarantees that your object isn't being
> altered).
>
> - Jonathan M Davis
It would be true if the delegate wasn't stored in c. For instance, it is
true if the delegate is passed as oops argument.
But in our case, the type system is broken. See explanations in other
posts I've made in this thread.
More information about the Digitalmars-d
mailing list