I'm going to assume that you really mean initialization, so that assignment after main
has started is out. This will not make a difference for basic types like int
or double
, but may make one for complex data types.
The answer is: no but yes (sort of). It is not possible to delay the initialisation of a static data member until after main
started, but you can use a static member function with a function-local static object to simulate the effect. This object will be initialized after the function is first called. In code:
#include <iostream>
struct A {
A() {
std::cout << "A::A()\n";
}
void do_something() {
std::cout << "A::do_something()\n";
}
};
struct B {
static A &a() {
static A instance;
return instance;
}
};
int main() {
std::cout << "main start\n";
B::a().do_something();
B::a().do_something();
std::cout << "main end\n";
}
This will print
main start
A::A()
A::do_something()
A::do_something()
main end
You would then use B::a()
where you'd have used B::a
before. You will have to make sure that the function is not called before main
is started.