c++ - How to comprehend that an implementation is permitted to treat dynamic initialization of non-local variable as static initialization in some cases? -
in fact, problem comes words in standard draft n4582:
[basic.start.static/3] implementation permitted perform initialization of variable static or thread storage duration static initialization if such initialization not required done statically, provided that
— dynamic version of initialization not change value of other object of static or thread storage duration prior initialization, and
— static version of initialization produces same value in initialized variable produced dynamic initialization if variables not required initialized statically initialized dynamically.
do these words mean if 2 conditions satisfied, non-local variable of class type may initialized statically (zero-initialized) constructor not called (since dynamic version, initializing calling constructor, may replaced static version)?
static initialization performed during compilation/linking. compiler/linker assigns location variable in static memory , fills correct bytes (the bytes don't need zeros). when program starts, regions of static memory loaded program's binary file , no further initialization required.
examples:
namespace { // statically zero-initialized int a; char buf1[10]; // non-zero initialized int b = 1; char date_format[] = "yyyy-mm-dd"; }
unlike static initialization, dynamic initialization requires running code after program start-up set initialized variables initial state. code needs run doesn't need constructor call.
examples:
namespace b { int = strlen(a::date_format); (1) int b = ++a; (2) time_t t = time(); (3) struct c { int i; c() : i(123) {} }; c c; (4) double s = std::sqrt(2); (5) }
now, c++ standard allows compiler perform computations carried out during dynamic initialization, provided computations not have side effects. besides, computations must not depend on external environment. in above example:
(1) can performed statically since strlen()
doesn't have side-effects.
(2) must stay dynamic since mutates a
.
(3) must stay dynamic since depends on external environment/makes system calls.
(4) can performed statically.
(5) little tricky, since floating point computation depends on state of fpu (namely, rounding mode). if compiler told not treat floating point arithmetic seriously, can performed statically.
Comments
Post a Comment