Question about static variable that define in a function
-
Hello all, Would anyone tell me that how C++ prevent the static variable been created more than one? Eg, if I have a function that contains a static variable:
void f() { static classA a; a.print(); } void main() { f(); f(); }
How C++ prevents the static variable "a" inside the function to be constructed twice rather than once? If I inline the function f(), will it still works? Thanks!!!:) Nacho -
Hello all, Would anyone tell me that how C++ prevent the static variable been created more than one? Eg, if I have a function that contains a static variable:
void f() { static classA a; a.print(); } void main() { f(); f(); }
How C++ prevents the static variable "a" inside the function to be constructed twice rather than once? If I inline the function f(), will it still works? Thanks!!!:) Nacho -
-
Hello, Yes, I know that the static will created only once. But I want to know how C++ actualy implement this. And I want to know whether doing inline of f() will break the rule? Thanks! Nacho:)
But I want to know how C++ actualy implement this, Well, how the compiler implements this feature is up to the compiler alone, I guess. You can assume the internally generated code will resemble in some way the following:
static bool __f_a_initialized=false;
static char __f_a_storage[sizeof(classA)];void f()
{
if(!__f_a_initialized){
new (__f_a_storage) class A; // constructs a classA onto __f_a_storage
__f_a_initialized=true;
}...
}Do not take this as the actual procedure implemented, it is just an approximation to what the compiler probably does. Does this answer your question? And I want to know whether doing inline of f() will break the rule? The rule does not break even if you declare your function
inline
. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo Want a Boost forum in Code Project? Vote here[^]!