为什么const_cast的行为不符合预期
Why does const_cast not behave as expected?
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
的。
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- C++概念assignable_from不接受 const&-return 运算符=
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 将 QByteArray 转换为无符号短:不符合预期
- 为什么此模板函数的行为不符合预期?
- 为什么 std::basic_ostream::运算符<<不符合 CONST 资格?
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- std::vector 构造initializer_list的行为不符合预期
- 为什么 std::uniform_int_distribution<IntType>::operator() 不是 const?
- C++使用 LZ4 进行压缩,压缩信息不符合预期
- 为什么 std::future::wait_for 的行为不符合预期?
- 有条件地传递修改后的副本而不是const原始副本变得丑陋
- 重载 * 运算符时不使用 const 的影响
- 在复制构造函数中使用和不使用 const 有什么区别
- Seekg 的行为不符合预期
- Int 附加到字符,行为不符合我的预期
- NDK r16b std::istringstream 的行为不符合预期
- 我应该始终使用"T&&"而不是"const T&"或"T&"来绑定到回调函数吗?
- 为什么std::is_copy_constructible的行为不符合预期
- 对指针行为不符合预期行为的 const 引用