It can be optimized, yes. But you still have some control over the process, for example, suppose the code:
int x = 1; x = 1; x = 1; x = 1; volatile int y = 1; y = 1; y = 1; y = 1;
Provided that neither x nor y are used below this fragment, VS 2010 generates code:
int x = 1;
x is 1;
x is 1;
x is 1;
volatile int y = 1;
010B1004 xor eax, eax
010B1006 inc eax
010B1007 mov dword ptr [y], eax
y = 1;
010B100A mov dword ptr [y], eax
y = 1;
010B100D mov dword ptr [y], eax
y = 1;
010B1010 mov dword ptr [y], eax
That is, optimization breaks all the lines into "x" and leaves all four lines with "y". This is how volatile works, but the fact is that you still have control over what the compiler does for you.
Whether it is a class or a primitive type - it all depends on the compiler, how complex its optimization restrictions are.
Another piece of code to learn:
class A { private: int c; public: A(int b) { *this = b; } A& operator = (int b) { c = b; return *this; } }; int _tmain(int argc, _TCHAR* argv[]) { int b = 0; A a = b; a = b; a = b; return 0; }
Optimization Visual Studio 2010 breaks all the code into nothing, in the release build with "full optimization" _tmain does nothing and immediately returns zero.
Roman R.
source share