删除volatile cv的原因是什么? [英] What the reason to remove volatile cv?

查看:158
本文介绍了删除volatile cv的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const_cast 可用于删除 volatile 限定符:

The const_cast can be used to remove volatile qualifier:

Quote:

特别是,只有const_cast可用于抛弃(删除)constness或volatility

In particular, only const_cast may be used to cast away (remove) constness or volatility

const_cast转换 - cppreference.com [ ^ ]



volatile 对象应该是 NOT 以这种方式访问​​:

const_cast conversion - cppreference.com[^]

But the volatile object should NOT be accessed that way:

Quote:

任何尝试引用volatile对象通过非易失性glvalue(例如通过引用或指向非易失性类型的指针)导致未定义的行为

Any attempt to refer to a volatile object through a non-volatile glvalue (e.g. through a reference or pointer to non-volatile type) results in undefined behavior

cv(const和volatile)类型限定符 - cppreference.com [ ^ ]



那么,重点是什么?



此外,在我看来,从实际的 const 对象中删除 const cv(存储在标记为const的内存页面中)导致分段错误



我尝试过:



我确认,当我试图通过 none volatile ref(使用<$ c)访问 volatile 对象时在 MS VS 2013 中的$ c> const_cast )它运行良好,通过编译在 MS VS 2015 它只是粉碎了,所以是的,这显然是UB 。

cv (const and volatile) type qualifiers - cppreference.com[^]

So, what the point?

Also, as i see it, removing the const cv from an actual const object (stored in the memory page marked as const) leads to the segmentation fault.

What I have tried:

I confirm that, when i was trying to access the volatile object by none volatile ref (using the const_cast) in MS VS 2013 it works fine, through compiled in MS VS 2015 it just crushed, so yep this is clearly UB.

推荐答案

这是一个kludge,让你调用非const遗留代码,你知道这些代码不会修改值,而是坚持非const参数。



基本上,如果您使用它,风险自负!
It's a kludge, to let you call non-const legacy code that you know won't modify the value but that insists on a non-const parameter.

Basically, if you use it, it's at your own risk!


没有理由使用<$去除波动率c $ c> const_cast 并且有非常罕见的情况,其中rem oving constness是有意义的。



警告非常清楚,它有时与特定编译器一起工作并不意味着它总能工作(它可能在运行期间失败) -time即使使用这样的编译器)。



只有在真正需要的时候才能使用删除constness,并确保没有副作用且真实数据是不恒定(例如你有一个由const指针引用的非const数组。)
There is no reason to remove volatility using const_cast and there are very rare situations where removing constness makes sense.

The warnings are quite clear and that it does work sometimes with a specific compiler does not mean that it will work always (it may fail during run-time even with such a compiler).

Removing constness should be used only when really necessary and you are sure that there will be no side effects and the real data is not constant (e.g. you have a non const array referenced by a const pointer).


这篇关于删除volatile cv的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆