M
Marijn
I'd like to know how compilers usually handle static variables that
are declared inside a function (as opposed to static class-members).
Like in:
int counter(){
static int c=0;
++c;
return c;
}
I would assume the compiler changes it into something like this:
bool counter_c_is_initialized = false;
int counter_c;
int counter(){
if (!counter_c_is_initialized){
c = 0;
counter_c_is_initialized = true;
}
++c;
return c;
}
Since they do not seem to be initialized when the function is never
called. Am i correct here? So if this is correct there will be an
extra conditional every time the function is called.
I've lately taken to implementing singletons with a static function
var, something like this:
class Singleton{
public:
static Singleton& get(){
static Singleton single;
return single;
}
private:
Singleton(){}
};
This only works if the constructor does not take arguments, but it
does take care of the destruction of the object when the program
terminates. Any problems with this form of singleons? I guess i do not
have precise control over the order in which such objects get
destructed, so if the destructor depends on another semi-global object
it could cause problems.
Marijn Haverbeke
are declared inside a function (as opposed to static class-members).
Like in:
int counter(){
static int c=0;
++c;
return c;
}
I would assume the compiler changes it into something like this:
bool counter_c_is_initialized = false;
int counter_c;
int counter(){
if (!counter_c_is_initialized){
c = 0;
counter_c_is_initialized = true;
}
++c;
return c;
}
Since they do not seem to be initialized when the function is never
called. Am i correct here? So if this is correct there will be an
extra conditional every time the function is called.
I've lately taken to implementing singletons with a static function
var, something like this:
class Singleton{
public:
static Singleton& get(){
static Singleton single;
return single;
}
private:
Singleton(){}
};
This only works if the constructor does not take arguments, but it
does take care of the destruction of the object when the program
terminates. Any problems with this form of singleons? I guess i do not
have precise control over the order in which such objects get
destructed, so if the destructor depends on another semi-global object
it could cause problems.
Marijn Haverbeke