为什么const_cast的行为不符合预期?

xml*_*lmx 7 c++ casting const copy-constructor c++11

struct A
{
    A() {}

private:
    A(const A&); // Explicitly disable the copy constructor.
};

int main()
{
    const A a1; // OK.
    A       a2; // OK.
    auto    a3 = const_cast<A&>(a1); // Compiler error C2248! ???       
}
Run Code Online (Sandbox Code Playgroud)

我的C++编译器是最新的VC++ 2013预览版.

编译器抱怨错误C2248的最后一行:'A :: A':无法访问在类'A'中声明的私有成员

为什么const_cast的行为不符合预期?

Mik*_*our 13

auto,它本身并不是一种参考类型.所以最后一行相当于

A a3 = const_cast<A&>(a1);
Run Code Online (Sandbox Code Playgroud)

尝试a1使用私有构造函数进行复制.

如果需要引用,则需要指定引用:

auto & a3 = const_cast<A&>(a1);
Run Code Online (Sandbox Code Playgroud)

当然,尝试使用此引用进行修改a1将给出未定义的行为,因为对象本身就是const.

  • @lulyon:不; `const_cast <A&>`的结果是对现有对象的引用.声明一个对象会生成一个新对象,这就是`auto a = whatever;`是什么(无论是`what`是一个引用). (5认同)