Search code examples
constantsdimmutabilitymember-functionsstorage-class-specifier

What is the difference between immutable and const member functions?


The D programming language reference shows two examples in the Declarations and Type Qualifiers section, so these are both possible:

struct S
{
    int method() const
    {
        //const stuff
    }
}

struct S
{
    int method() immutable
    {
        //immutable stuff
    }
}

From the docs:

Const member functions are functions that are not allowed to change any part of the object through the member function's this reference.

And:

Immutable member functions are guaranteed that the object and anything referred to by the this reference is immutable.

I've found this question, but all the answers are talking about data types, not storage classes. Same goes for the D const FAQ, even though it's an interesting read.

So what is the difference between the two definitions above? Are there expressions that can replace //const stuff and be legal but not //immutable stuff?


Solution

  • immutable methods may only be called on immutable objects. They can work with the guarantee* that their object (this) will not change, ever.

    const methods may be called on const, immutable, or mutable objects. They guarantee that they themselves will not change their object, but other references may change the object.

    I'd go with const unless you have a good reason to need immutable, as const functions are callable with all three mutability storage classes.


    * At the type system level, anyway. Mutating an immutable object is possible, but causes undefined behavior.