Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile vs. mutable in C++

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?

Thanks a lot.

like image 730
skydoor Avatar asked Mar 15 '10 02:03

skydoor


People also ask

What is a mutable variable in C?

Mutable keyword in C++?Mutable data members are that kind of member, which can be changed always. Even if the object is const type. When we need only one member as variable and other as constant, then we can make them mutable.

What is the difference between volatile and non volatile variable in C?

1. Volatile memory is the type of memory in which data is lost as it is powered-off. Non-volatile memory is the type of memory in which data remains stored even if it is powered-off.

Is volatile in standard C?

C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.

Does C++ have volatile?

Here we will see what is the meaning of volatile qualifier in C++. The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time.


1 Answers

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.

like image 188
Alex Martelli Avatar answered Sep 29 '22 00:09

Alex Martelli