Am Mon, 14 May 2012 16:54:34 -0700
schrieb Walter Bright <[email protected]>:
> On 5/14/2012 10:08 AM, Tove wrote:
> > but c++ has the 'mutable' keyword as an easy escape route...
>
> The existence of that capability means that 'const' in C++ cannot be
> meaningfully reasoned about.
class Foo
{
uint a, b;
// can only call const pure nothrow members here:
lazy uint somethingLazyInitialized = { return 2 * bar(); }
uint bar() const pure nothrow @safe
{
// complex calculation
return a + b;
}
override uint toHash() const pure nothrow @safe
{
// sets the field on the first use
return somethingLazyInitialized;
}
}
Internally the "lazy uint" consists of a function pointer and the uint. A lazy
field acts like a read-only property. Whenever the field is read, code is
generated that first checks, if the function pointer is not null. It then
updates the uint with the return value of the function call and sets the
function pointer to null, to indicate that the value is now initialized.
An instance of Foo cannot be immutable (it makes no sense to ask for that with
lazy initialization), but it can be const. This is a form of logical const that
still allows reasoning about the code + compiler enforcement in contrast to the
more flexible (in a positive and negative sense) C++ mutable.
--
Marco