现在我必须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.
以上是内存溢出为你收集整理的c – 使用const_cast的自动类型推断不起作用全部内容,希望文章能够帮你解决c – 使用const_cast的自动类型推断不起作用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)