丢弃 const 限定符

Discarding const qualifier

为什么不允许丢弃 const 限定符?假设我们写:

#include <iostream>

struct A
{
    void operator=(const A&){ std::cout << "A&" << std::endl; }
    void operator=(const A&&){ std::cout << "A&&" << std::endl; }
};

const A a;
A b;

int main()
{
    a = b; //Error: discarding qualifier
}

有人不能提供标准不允许的参考吗?

问题是 aconst,因此不允许 operator=,它应该修改被调用的对象。这是由const-正确性引起的。

operator= 声明为 const 是没有意义的,因为 operator= 的语义是它应该用右侧值修改调用它的对象,并且return 对左侧对象的 T& 引用,如果左侧对象是 const(不包括 const_cast 用法),则这是不可能的。

另一方面,允许以下内容:

int main()
{
    A b;
    const A a = b;
}

因为在那种情况下它是构造一个新的常量对象。


正如您所说,该标准在 §9.3.2/3 中使用以下措辞对此进行了指定:

A cv-qualified member function can be called on an object-expression (5.2.5) only if the object-expression is as cv-qualified or less-cv-qualified than the member function.