不可变成员函数和常量成员函数有什么区别?

What is the difference between immutable and const member functions?

D 编程语言参考在 Declarations and Type Qualifiers 部分显示了两个示例,所以这些都是可能的:

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

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

来自文档:

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

并且:

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

我找到了 this question, but all the answers are talking about data types, not storage classes. Same goes for the D const FAQ,尽管这是一本有趣的书。

那么上面两个定义有什么区别呢?有没有可以代替//const stuff合法但//immutable stuff不合法的表达式?

immutable 方法只能在 immutable 个对象上调用。他们可以保证*他们的对象 (this) 永远不会改变。

const 方法可以在 constimmutable 或可变对象上调用。他们保证自己不会改变自己的对象,但其他引用可能会改变对象。

除非你有充分的理由需要 immutable,否则我会选择 const,因为 const 函数可以使用所有三个可变性存储 类 调用。


* 无论如何,在类型系统级别。改变不可变对象是可能的,但会导致未定义的行为。