+1 vote
in D Programming by
What Is Logical Const?

1 Answer

0 votes
by

Logical const refers to data that appears to be constant to an observer, but is not actually const. An example would be an object that does lazy evaluation:

struct Foo

{

    mutable int len;

    mutable bool len_done;

    const char* str;

    int length()

    {

        if (!len_done)

        {

            len = strlen(str);

            len_done = true;

        }

        return len;

    }

    this(char* str) { this.str = str; }

}

const Foo f = Foo("hello");

bar(f.length);

The example evaluates f.len only if it is needed. Foo is logically const, because to the observer of the object its return values never change after construction. The mutable qualifier says that even if an instance of Foo is const, those fields can still change. While C++ supports the notion of logical const, D does not, and D does not have a mutable qualifier.

The problem with logical const is that const is no longer transitive. Not being transitive means there is the potential for threading race conditions, and there is no way to determine if an opaque const type has mutable members or not.

Related questions

+1 vote
asked Mar 5, 2021 in D Programming by SakshiSharma
0 votes
asked Jan 17 in Oracle by kamalkhandelwal29
...