为什么 const_castaway 易失性只适用于指针

发布于 2024-12-16 21:39:42 字数 298 浏览 3 评论 0原文

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

記憶穿過時間隧道 2024-12-23 21:39:42

const_cast 作用于指针和引用,以删除 const易失性 限定符。使用它来转换为对象类型是没有意义的,因为这样您就可以制作一个副本,该副本不需要与原始副本具有相同的 cv 限定符。

如果您转换为非易失性引用,您的第二个示例将进行编译:

volatile CString b0;
CString & b1 = const_cast<CString &>(b0);

但是,使用该引用会产生未定义的行为,因为底层对象本身是易失性的。仅当您知道基础对象不具有这些限定时(或者在删除 const 的情况下,当您知道结果不会用于修改对象时)。

仅当对象允许复制易失性对象时(可能使用采用易失性引用或易失性限定函数或转换运算符的复制构造函数),您才能获得副本。如果CString不提供任何这些,那么您就无法安全地复制该类型的易失性对象。

const_cast acts on pointers and references, to remove const and volatile 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:

volatile CString b0;
CString & b1 = const_cast<CString &>(b0);

However, using that reference gives undefined behaviour, since the underlying object is itself volatile. You should only use const_cast to remove qualifications when you know that the underlying object does not have those qualifications (or in the case of removing const, 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 a volatile object of that type.

红焚 2024-12-23 21:39:42

因为在第二种情况下,您实际上是在复制 b0 而不是引用原始对象,

在这种情况下您需要进行引用

const CString &b1 = b0;

because in the second case you are actually copying b0 and not referring to the original object

you need to do a reference in that case

const CString &b1 = b0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文