C++ volatile object, nonvolatile member -
as in question: let's have small piece of code this:
#include <iostream> using namespace std; struct foo { int a; foo() : a(12) {}; }; int main() { volatile foo x; return 0; }
compiled g++ -g -o2
turns out, x
initialization optimized away.
that 1 however:
#include <iostream> using namespace std; struct foo { volatile int a; foo() : a(12) {}; }; int main() { volatile foo x; return 0; }
calls constructor.
if try use variables inside code, (ie. cout << foo.a << endl;
) assembly output equivalent in both cases.
do following right, that:
in first case, there's no access struct @ all, gets optimized away completely.
in second one, struct's field indicated 1 possible change during construction , reason foo() called no matter what.
added: i've tried fiddling above code: calling things while(foo.a--);
works expected, happens instead of being deleted/replaced result during optimization, seems volatile inherited, yet ctor behaves in strange (or @ least unexpected @ first) way.
edit number 2:
i checked clang , msvc , behaves same way in gcc.
my understanding follows (and not sure it):
in c++ volatile
keyword forces compiler not optimize seemingly redundant loads , stores memory, i.e. if have such example code:
int x = 5; x = 6;
it not changed to:
int x = 6;
this because x
pointing address in memory, read others, while don't read in program (imagine sending configuration on usart microcontroller writing memory address, , microcontroller reads it's configuration address - if compiler optimize writes memory, whole program malfunction).
another thing 1 must remember when instance of class declared volatile
specifier, members inherit specifier (as igor tandetnik pointed out in comment, referring c++ standard). not whole truth, because in order volatile
behaviour, have call member functions, marked volatile
- similar marking member function const
(please see this: http://www.devx.com/tips/tip/13671). because afaik ctors/dtors cannot marked volatile
keyword (as in defining volatile class object), have change code bit (perhaps invoking volatile member function within ctor thing, guess).
Comments
Post a Comment