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

Why does const_cast not behave as expected?

本文关键字:不符合 const cast 为什么      更新时间:2023-10-16
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! ???       
}

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

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

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

auto本身从来都不是引用类型。所以最后一行相当于

A a3 = const_cast<A&>(a1);

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

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

auto & a3 = const_cast<A&>(a1);

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