在文件maybe_use_foo.cpp中:
namespace {
class Foo { /* ... */ };
Foo* const the_foo = new Foo;
}
void funtion_callable_from_another_tu_during_process_wide_initialization() {
// If we haven't yet run static initialization for this TU,
// but some other static initializer called us, ignore the request.
if (!the_foo)
return;
// OK, static initializers for this TU have run, foo exists, use it.
the_foo->doSomething();
}
所以,不管上述方法是否可取,它总是有效的吗?在我看来,它假设静态变量在TU的静态初始化之前被零初始化。C++标准(C++03?C++11?)是否保证了这一点?
另一种提问方式是询问哪个值序列,当解释为Foo*时,保存在“the_foo”的存储器中。它肯定是{NULL/nullptr,new Foo}吗?还是{未定义,new Foo},甚至是其他东西?
请不要建议其他组织方式:我不是在寻求如何更好地完成此任务的建议,而是在寻求对该技术合法性的深入理解。
Loki loki(5);
这个呢?在动态初始化之前是否进行了零初始化。构造函数不是constexpr
。因此不符合constant-initialization
的要求。 - Martin York