[英]Static local variables' initialization at program startup
cppreference狀態:
在塊 scope 處使用說明符 static 或 thread_local (C++11 起)聲明的變量具有 static 或線程 (C++11 起)存儲持續時間,但在控件第一次通過它們的聲明時被初始化(除非它們的初始化為零或constant-initialization ,可以在第一次進入塊之前執行)。
我的問題是關於“除非”部分——你能給出 static 局部變量被零初始化和常量初始化的代碼示例嗎? class 對象(例如MyClass obj;
)可以零初始化還是常量初始化? 如果是這樣,是否意味着它們的構造函數將在main()
啟動之前被調用?
你能給出 static 局部變量被零初始化和常量初始化的代碼示例嗎?
在下面給出的示例中,本地變量 static n
滿足常量初始化的兩個條件,因此此處引用語句中的“除非”部分也成立。
int main()
{
static const int i = 5; //both conditions for constant initialization are satisfied so that the "unless" part of your quoted statement also holds
}
變量或臨時 object
obj
是常量初始化的,如果
它要么有一個初始化器,要么它的默認初始化導致執行一些初始化,並且
它的初始化全表達式是常量表達式,除了如果 obj 是一個 object,則該全表達式也可以為 obj 及其子對象調用 constexpr 構造函數,即使這些對象是非文字 class 類型 (C++11 起) .
class 對象(例如
MyClass obj;
)可以零初始化還是常量初始化?
是的 class 對象也可以常量初始化。
struct Custom
{
constexpr Custom()
{
}
};
int main()
{
static constexpr Custom obj;//here also both conditions for constant initialization are satisfied
}
另請注意,初始化並不一定意味着必須使用構造函數。 例如,在#include <string> std::string s; int main(){}
#include <string> std::string s; int main(){}
s
首先是零初始化,然后是默認初始化(使用默認構造函數)。 這意味着這里的第一個初始化步驟不使用任何構造函數。
根據這個: https://en.cppreference.com/w/cpp/language/zero_initialization
執行零初始化 [...] 對於每個具有 static [...] 存儲持續時間且不受常量初始化約束的命名變量,在任何其他初始化之前。
所以在這種情況下
int main() {
...
static MyClass a;
...
}
a
零初始化可以在main()
開始之前執行,但它的構造函數將按預期在main()
內部調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.