As in the question: let's say I have a small piece of code like this:
#include <iostream>
using namespace std;
struct foo {
int a;
foo() : a(12) {};
};
int
main()
{
volatile foo x;
return 0;
}
compiled with g++ -g -O2
it turns out, that x
initialization is optimized away.
That one however:
#include <iostream>
using namespace std;
struct foo {
volatile int a;
foo() : a(12) {};
};
int
main()
{
volatile foo x;
return 0;
}
calls the constructor.
If I try to use the variables inside the code, (ie. cout << foo.a << endl;
) the assembly output is equivalent in both cases.
Do I get the following right, that:
In the first case, there's no access to the struct at all, so it gets optimized away completely.
In the second one, struct's field is indicated as the one possible to change also during the construction and for that reason foo() is called no matter what.
Added:
I've tried fiddling with the above code:
calling things like while(foo.a--);
works as expected, it actually happens instead of being deleted/replaced by result during optimization, thus it seems the volatile is actually inherited, yet the ctor behaves in this strange (or at least unexpected at first) way.
EDIT number 2:
I checked it with clang and MSVC and it behaves the same way as in gcc.