在C ++中是易变的 [英] volatile vs. mutable in C++

查看:219
本文介绍了在C ++中是易变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于volatile和mutable之间的区别的问题。我注意到两者都意味着它可以改变。还有什么?他们是同样的东西吗?有什么不同?它们在哪里适用?为什么提出这两个想法?如何以不同的方式使用它们?

I have a question about the difference between volatile and mutable. I noticed that both of the two means that it could be changed. What else? Are they the same thing? What's the difference? Where are they applicable? Why the two ideas are proposed? How to use them in different way?

非常感谢。

推荐答案

A mutable a const 指针或引用,或者在 const 对象中,因此编译器知道不要将其存储在R / O记忆。 A volatile 位置是可以由编译器不知道的代码(例如,某些内核级驱动程序)更改的位置,因此编译器知道不优化。在该值自上次加载到该寄存器之后值不可能已经改变的无效假设下的该值的寄存器分配。非常不同种类的信息被给予编译器以停止非常不同种类的无效优化。

A mutable field can be changed even in an object accessed through a const pointer or reference, or in a const object, so the compiler knows not to stash it in R/O memory. A volatile location is one that can be changed by code the compiler doesn't know about (e.g. some kernel-level driver), so the compiler knows not to optimize e.g. register assignment of that value under the invalid assumption that the value "cannot possibly have changed" since it was last loaded in that register. Very different kind of info being given to the compiler to stop very different kinds of invalid optimizations.

这篇关于在C ++中是易变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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