Logical const
Steven Schveighoffer
schveiguy at yahoo.com
Mon Nov 29 11:01:07 PST 2010
On Mon, 29 Nov 2010 11:53:27 -0500, Michel Fortin
<michel.fortin at michelf.com> wrote:
> On 2010-11-29 11:24:56 -0500, "Steven Schveighoffer"
> <schveiguy at yahoo.com> said:
>
>> On Mon, 29 Nov 2010 10:56:14 -0500, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org> wrote:
>>
>>> In fact it's possible to provide logical const with guarantees. You
>>> need a construct that keeps together a bool, a pure
>>> function/delegate/method, and a value, and works like this:
>>> class X
>>> {
>>> int x;
>>> lconst int y = { return x + 42; };
>>> void m1() { x = 2; invalidate(y); }
>>> void m2() const { writeln(y); }
>>> }
>>> You can use the intrinsic invalidate() against a non-const lconst
>>> field, but not against const lconst. Reading that field checks
>>> whether the field has been invalidated. If so, it writes the field
>>> with the result of the function/delegate/method and turns the
>>> validation flag on.
>>> With this system in place, I think the lconst value is guaranteed to
>>> be as strong as const.
>> This only solves the caching issue (which I agree is a large issue).
>> There are other cases where you want a mutable pointer to other data
>> that the object does not own. Such as a widget having a pointer to
>> its window. Assuming that window draw routines need to be non-const,
>> a widget cannot draw itself. You need to keep the widget to window
>> relationship outside the class, or cast. Both of these solutions are
>> awkward at best.
>
> You can pass the drawing context (the window in your case) as an
> argument do the draw function.
That's the "keep the relationship outside the class" solution. I find
this solution substandard -- a widget should know where it is located.
Another solution I didn't mention is to just not mark draw as const, and
then you just have to follow the convention that draw should not mutate
any internal state. I don't like this either.
-Steve
More information about the Digitalmars-d
mailing list