现在我必须const_cast一些非常复杂的类型,实际上我不想在const_cast< Clutter>中写出所有这种类型的混乱.表达式,特别是如果Clutter非常长.
我的第一个想法是编写const_cast<>(myType),但是我的编译器无法推导出myType的非const类型.所以我想帮助我的编译器和我编写以下方法,编译.
#include <stdlib.h> #include <iostream> int main(int, char**) { const int constVar = 6; using T = typename std::remove_cv<decltype(constVar)>::type; auto& var = const_cast<T&>(constVar); var *= 2; std::cout << &constVar << " " << &var << "\n"; // Same address! std::cout << constVar << " " << var << "\n"; return EXIT_SUCCESS; }
不幸的是,程序给了我输出6 12而不是预期的6 6,我真的不明白?
我的做法有什么问题?
从const_cast
的文档:
const_cast
makes it possible to form a reference or pointer to non-const type that is actually referring to a const object or a reference or pointer to non-volatile type that is actually referring to a volatile object. Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.
所以你拥有的是未定义的行为.
同样令人感兴趣的是cv type qualifiers的这张纸条.
const object – an object whose type is const-qualified, or a non-mutable subobject of a const object. Such object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.