忽略C ++拷贝构造函数的const正确性?

时间:2013-07-25 15:34:54

标签: c++ const copy-constructor

采用此示例代码

#include <iostream>

using namespace std;
class Address
{
  public:
    mutable unsigned key;

    Address() : key(0) {};
    Address(int a) : key(a) {};

    // const Address but compiler lets us modify it anyway!
    Address(const Address &n) : key(++n.key) {};
    void showKey() { cout << "key is " << key << endl;}
    void modifyKey(int k) { key = k;}
};

int main()
{
  cout << "Address a " << endl;
  Address a;
  a.showKey();

  cout << "Address b " << endl;
  Address b(a);
  b.showKey();

  if (b.key == a .key)
    cerr << "Wow the compiler doesn't care about const correctness" << endl;

  return 0;
}

Address类的复制构造函数如果引用常量n对象,则表示Address。因此,我希望不允许修改n引用的对象。似乎编译器允许直接操作n的字段。但是我确实注意到我是否在地址中添加了非const方法,并在复制构造函数(例如n)内的n.myNonConstMethod()上调用它,编译器会抱怨。

我很惊讶这段代码编译(我已经尝试过g ++和clang ++,他们编译时没有错误或警告)。我是否误解了const的使用(这不是第一次!)或者是这些编译器错误?

1 个答案:

答案 0 :(得分:3)

Pulled from MSDN

  

此关键字[mutable]只能应用于类的非静态和非常量数据成员。如果数据成员被声明为可变,那么从const成员函数为该数据成员赋值是合法的。

相关问题