I'm pretty new to C++ and recently I ran across some info on what it means for a variable to be volatile
.As far as I understood, it means a read or write to the variable can never be optimized out of existence.
However a weird situation arises when I declare a volatile
variable that isn't 1, 2, 4, 8 bytes large: the compiler(gnu with C++11 enabled) seemingly ignores the volatile
specifier. Code kinda looks like this:
#define expand1 a, a, a, a, a, a, a, a, a, a
#define expand2 //ten expand1 here, expand3 to expand5 follows
struct threeBytes{char x,y,z;};
int main()
{
foo<int>();
foo<threeBytes>();
}
template<typename T>
void foo()
{
volatile T a;
//time an empty for loop
//run expand5 for 1e+005 times
//compare time difference and print result
}
The result is the int
version will give me ~1.5 seconds while the threeBytes
version will give exactly 0. I've tested it with different variables(user-defined or not) that is 1 to 8 bytes and only 1, 2, 4, 8 takes time to run. Is this a bug only existing on my PC or is volatile
a request to the compiler and not something absolute?
PS the four byte versions always take half the time as others on my PC and is also a source of confusion
Aucun commentaire:
Enregistrer un commentaire