newsock said:
Why need to qualify a member function "volatile"?
It has a similar effect to declaring a member function "const":
The "this" pointer will point to a "volatile"-qualified equivalent
of the class type.
Why need to qualify a object "volatile"?
It forces the object's value to actually be checked each and
every time it is read. For example, in the following:
int foo = 2;
std::cout << foo;
A compiler would be well within its rights to optimize the second
line to:
std::cout << 2;
Since it knows that foo was not changed from its initial value
before the output. However, if it were declared:
volatile int foo = 2;
std::cout << foo;
The volatile keyword says that foo may be changed by some
mechanism *outside* of the program, so the compiler had better
double-check the value of foo before deciding to output it to
std::cout.
This is mainly useful if the is registered somehow by address
with an external process/thread, or in code such as the
following:
volatile int *foo = reinterpret_cast<int *>( 0x01f0 );
*foo = 2;
std::cout << *foo;
In the above example, foo is now a pointer to volatile int, whose
location is a hard-coded value that perhaps has some special
meaning in the system for which this particular program was
written: it might be that this value is mapped to (say) the
number of milliseconds this process has been running; or maybe
it's a pixel in video memory. Your program doesn't "know" this,
but it does know that this is a "special" int, and it should
assume that its value may have changed while it wasn't paying
attention.
When need to "const_cast" away "volatile" of an object and a member
function?
It's never needed; but provided that you were *sure* that an
object really isn't going to be changed on the sly, you could
cast it away for a potential efficiency boost.
I also saw some code of a function argument of "volatile" type. What's the
purpose there?
Are you sure? It has no purpose there: it is thrown out (as is
const). However, a parameter with a type *derived* from a
volatile type (say, pointer-to-volatile-something-or-other) could
be significant.
class vClass
{
void foo() volatile {}
void boo(){}
};
int main()
{
volatile vClass v;
v.foo(); //no problem
v.boo(); //compile error
Right. Same reason why it would fail if you changed the instances
of "volatile" in this snippet to "const": "this" points to a
volatile vClass, but boo() doesn't "accept" a volatile "this"; a
compiler would typically compile boo() with optimizations that
don't require that members of vClass (had they existed) be
checked for on-the-sly changes, which would not be acceptable for
instances that have been declared with the "volatile" qualifier.
No prob!