标签:const-cast c templates visual-studio-2015
在我的工作中,const_cast的使用在某些情况下是不可避免的.
现在我必须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.
标签:const-cast,c,templates,visual-studio-2015 来源: https://codeday.me/bug/20190731/1586139.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。