gpt4 book ai didi

c++ - 静态内联变量是否需要在main之前初始化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:39 25 4
gpt4 key购买 nike

如果我有以下 A.h 文件(仅 header ):

#pragma once

struct A{
static inline struct Initializer{
Initializer(){
std::cout << "init A" << std::endl;
}
} initializer;
};

#include "A.h"(来自另一个 header ,将包含在 main.cpp 中)是否足够,所以 Initializer::Initializer() 之前被调用main()?

我读到标准要求仅在使用前使用动态初始化来初始化静态变量。

It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.

#include 是否被视为“使用”?

最佳答案

最新的工作草案在[basic.start.dynamic]/5中有更明确的措辞:

It is implementation-defined whether the dynamic initialization of a non-local inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of that variable. It is implementation-defined in which threads and at which points in the program such deferred dynamic initialization occurs.

地点:

A non-initialization odr-use is an odr-use ([basic.def.odr]) not caused directly or indirectly by the initialization of a non-local static or thread storage duration variable.


因此,回答你的问题:

Is it enough to #include "A.h" (from another header, which will be included by main.cpp) so Initializer::Initializer() be called before main()?

没有。 #include 是不够的。你实际上必须 odr-use它。

关于c++ - 静态内联变量是否需要在main之前初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com