为什么 const_castaway 易失性只适用于指针
// OK!
volatile CString* a0;
CString* a1 = const_cast<CString *>(a0);
// error C2440: 'const_cast' : cannot convert from 'volatile CString' to 'CString'
volatile CString b0;
CString b1 = const_cast<CString>(b0);
我想知道,为什么 const_cast 只适用于指针?我怎样才能编译第二种情况?
// OK!
volatile CString* a0;
CString* a1 = const_cast<CString *>(a0);
// error C2440: 'const_cast' : cannot convert from 'volatile CString' to 'CString'
volatile CString b0;
CString b1 = const_cast<CString>(b0);
I was wondering, why const_cast
only work for pointer? How can I make the 2nd case to compile?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
const_cast
作用于指针和引用,以删除const
和易失性
限定符。使用它来转换为对象类型是没有意义的,因为这样您就可以制作一个副本,该副本不需要与原始副本具有相同的 cv 限定符。如果您转换为非易失性引用,您的第二个示例将进行编译:
但是,使用该引用会产生未定义的行为,因为底层对象本身是易失性的。仅当您知道基础对象不具有这些限定时(或者在删除
const
的情况下,当您知道结果不会用于修改对象时)。仅当对象允许复制易失性对象时(可能使用采用易失性引用或易失性限定函数或转换运算符的复制构造函数),您才能获得副本。如果
CString
不提供任何这些,那么您就无法安全地复制该类型的易失性
对象。const_cast
acts on pointers and references, to removeconst
andvolatile
qualifiers. It doesn't make sense to use it to cast to an object type, since then you would making a copy which need not have the same cv-qualifiers as the original anyway.Your second example will compile if you cast to a non-volatile reference:
However, using that reference gives undefined behaviour, since the underlying object is itself
volatile
. You should only useconst_cast
to remove qualifications when you know that the underlying object does not have those qualifications (or in the case of removingconst
, when you know that the result won't be used to modify the object).You can only get a copy if the object allows copying of volatile objects (perhaps with a copy constructor taking a reference-to-volatile or a volatile-qualified function or conversion operator). If
CString
doesn't provide any of these, then you can't safely copy avolatile
object of that type.因为在第二种情况下,您实际上是在复制
b0
而不是引用原始对象,在这种情况下您需要进行引用
because in the second case you are actually copying
b0
and not referring to the original objectyou need to do a reference in that case