In the following code:
int count(){
static int n(5);
n = n + 1;
return n;
}
the variable n is instantiated only once at the first call to the function.
There should be a flag or something so it initialize the variable only once.. I tried to look on the generated assembly code from gcc, but didn’t have any clue.
How does the compiler handle this?
This is, of course, compiler-specific.
The reason you didn’t see any checks in the generated assembly is that, since
nis anintvariable,g++simply treats it as a global variable pre-initialized to 5.Let’s see what happens if we do the same with a
std::string:The generated assembly goes like this:
The line I’ve marked with the
bypass initializationcomment is the conditional jump instruction that skips the construction if the variable already points to a valid object.