M
Marcel Müller
Hi,
the following code
#include <stdio.h>
struct A
{ A() { puts("A()"); }
~A() { puts("~A()"); }
};
static const A& foo()
{ puts("foo()");
static const A var;
return var;
}
int main()
{
puts("main()");
foo();
foo();
return 0;
}
prints
main()
foo()
A()
foo()
~A()
So var inside foo is initialized after the first pass of the code over
the variable definition. Well, that would be useful in conjunction with
templates to achieve late initialization and avoid static initialization
dependencies.
But is this execution order guaranteed? (I guess yes.) And if so, what
does this mean with respect to threads?
If this is not thread safe one could never store non POD constants in
local statics in a multi threaded application, even if the underlying
object type provides thread safety for const methods, isn't it?
Marcel
the following code
#include <stdio.h>
struct A
{ A() { puts("A()"); }
~A() { puts("~A()"); }
};
static const A& foo()
{ puts("foo()");
static const A var;
return var;
}
int main()
{
puts("main()");
foo();
foo();
return 0;
}
prints
main()
foo()
A()
foo()
~A()
So var inside foo is initialized after the first pass of the code over
the variable definition. Well, that would be useful in conjunction with
templates to achieve late initialization and avoid static initialization
dependencies.
But is this execution order guaranteed? (I guess yes.) And if so, what
does this mean with respect to threads?
If this is not thread safe one could never store non POD constants in
local statics in a multi threaded application, even if the underlying
object type provides thread safety for const methods, isn't it?
Marcel