简体   繁体   English

全局变量的初始化是否与 function 内部变量 static 的初始化相同

[英]Is the initialization of global variable the same as the initialization of static variable inside a function

I'm trying to figure out all different kinds of initialization in C++.我试图找出 C++ 中所有不同类型的初始化。 Now I'm reading this link: https://en.cppreference.com/w/cpp/language/zero_initialization现在我正在阅读这个链接: https://en.cppreference.com/w/cpp/language/zero_initialization

In the example of this link, we have such a piece of code:在这个链接的例子中,我们有这样一段代码:

std::string s; // zero-initialized to indeterminate value
               // then default-initialized to ""

As my understanding, the initialization of the global variable is as below:据我了解,全局变量的初始化如下:

When we compile the code, the s is zero-initialized, it is put at the .bss segment of the binary file.当我们编译代码时, s是零初始化的,它被放在二进制文件的.bss段中。 When we run the binary file (meaning that the kernel is starting to load the binary file into RAM), the s is default-initialized to the empty string "" .当我们运行二进制文件时(意味着 kernel 开始将二进制文件加载到 RAM 中), s默认初始化为空字符串""

Now, we define a function as below:现在,我们定义一个 function 如下:

void func()
{
    static std::string s;
}

If we call the function first time, the s will be initialized, this is for sure.如果我们第一次调用 function, s将被初始化,这是肯定的。 But is it still initialized with two methods: first zero initialization, then default initialization, just like the first s ?但是它是否仍然使用两种方法进行初始化:首先是零初始化,然后是默认初始化,就像第一个s一样?

BTW, I'm working on Ubuntu, X86_64 architecture with the compiler GCC 7.5.顺便说一句,我正在使用编译器 GCC 7.5 研究 Ubuntu、X86_64 架构。 If my question is not standardized by C++, you could tell me in the comment and I'll close this question.如果我的问题没有被 C++ 标准化,你可以在评论中告诉我,我会关闭这个问题。

But is it still initialized with two methods: first zero initialization, then default initialization, just like the first s?但是还是用两种方法初始化:先零初始化,再默认初始化,和第一个s一样吗?

Assuming, the "as-if"-rule effectively forces the compiler to consider the existence of this variable, yes.假设,“as-if”规则有效地强制编译器考虑这个变量的存在,是的。 Excerpts from the standard:标准摘录:

Zero initialization is performed in the following situations:在以下情况下执行零初始化:

  1. For every named variable with static or thread-local storage duration that is not subject to constant initialization, before any other initialization.对于每个具有 static 的命名变量或不受常量初始化的线程本地存储持续时间,在任何其他初始化之前。

Default initialization is performed in three situations:默认初始化在三种情况下执行:

  1. when a variable with automatic, static, or thread-local storage duration is declared with no initializer;当一个具有自动、static 或线程本地存储持续时间的变量声明为没有初始化程序时;

As molbdnilo said within the comments, you should avoid thinking in terms of binary files, kernel and segments here totally if you are only interested in the behavior the standard claims.正如 molbdnilo 在评论中所说,如果您只对标准声称的行为感兴趣,则应完全避免考虑二进制文件、kernel 和此处的段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM