c++ - When is constructor's code of a class defined in global space running? -
class testclass { public: int x, y; testclass(); }; testclass::testclass() { cout << "testclass ctor" << endl; } testclass globaltestclass; int main() { cout << "main " << endl; return 0; }
in code known first output "testclass ctor"
.
my question: ctor function call codes run before main()
(i mean, entry point change ?) , or right after main()
, before executable statements or there different mechanism ? (sorry english)
the question stated not meaningful, because
main
not machine code level entry point program (main
called same code e.g. executes constructors of non-local static class type variables), and- the notion of “right after
main()
, before executable statements” isn't meaningful: executable statements inmain
.
generally, in practice can count on static variable being initialized before main
in concrete example, standard not guarantee that.
c++11 §3.6.2/4:
” implementation-defined whether dynamic initialization of non-local variable static storage duration done before first statement of
main
. if initialization deferred point in time after first statement ofmain
, shall occur before first odr-use (3.2) of function or variable defined in same translation unit variable initialized.
it's fine point whether automatic call of main
qualifies odr-use. think not, because 1 special property of main
cannot called (in valid code), , address cannot taken.
apparently above wording in support of dynamically loaded libraries, , constitutes support of such libraries.
in particular, wary of using thread local storage dynamically loaded libraries, @ least until learned more guarantees offered standard in respect.
Comments
Post a Comment