c++ - "static initialization"到底是什么意思?

标签 c++ c++11

我一直在阅读有关 C++11 中的 POD 的文章,我读过的几个地方都提到了支持静态初始化的 POD。例如:

On StackOverflow :

The idea of a POD is to capture basically two distinct properties:
1. It supports static initialization, and
2. Compiling a POD in C++ gives you the same memory layout as a struct compiled in C.

(只有粗体部分是相关的)

On Wikipedia :

A type that is trivial can be statically initialized.

显然我不明白什么是静态初始化。我认为制作全局变量是静态初始化的一个示例,但我可以执行以下操作,但 Foo 不是 POD:

#include <type_traits>
#include <iostream>

struct Foo {
  Foo() : x(0), y(0) {}
  int x;
  int y;
};

struct Bar {
  Bar() = default;
  int x;
  int y;
};

// Apparently the following two lines are not "static initialization" because
// Foo is non-POD yet we can still do this:
Foo f;
Bar b;

int main()
{
    if (std::is_pod<Foo>::value) std::cout << "Foo is a POD" << std::endl;
    else                         std::cout << "Foo is *not* a POD" << std::endl;

    if (std::is_pod<Bar>::value) std::cout << "Bar is a POD" << std::endl;
    else                         std::cout << "Bar is *not* a POD" << std::endl;
}

Output :

Foo is *not* a POD
Bar is a POD

那么到底什么是静态初始化,它与普通类有什么关系呢?例子会很棒。

最佳答案

静态初始化是使用编译时值初始化某些变量,这样该值最终被“烘焙到”可执行镜像中(不需要实际运行代码):

struct Foo {
  int x;
  int y;
};

Foo foo = { 0, 1 };

在上面的例子中,struct Foo 是 POD,所以编译器知道它的内存布局只是两个相邻的整数。它还知道 foo.x 应该初始化为 0foo.y 应该初始化为 1。这些信息足以生成foo 在编译时应该如何显示的“内存镜像”,并将其写入可执行镜像。

当图像稍后运行时,操作系统加载器将其内容映射到内存地址,并以这种方式使 foo“活着”。重要的是 foo 的“初始化”实际上已经在进程(包括您的代码以及来自 C/C++ 运行时的代码,它们首先运行)有时间执行之前完成甚至是单个 CPU 指令。

关于c++ - "static initialization"到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094514/

相关文章:

c++ - shared mutex 和 mutex 之间的区别(为什么两者都存在于 C++ 11 中)?

c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序

c++ - 类成员函数的 SFINAE(一个编译另一个不编译)

c++ - 前向声明类枚举问题的解决方法?

c++ - 为什么下面的类模板匹配不二义?

c++ - 另一个 "pointer being freed was not allocated"

c++ - 为什么声明为指向字符的指针并分配了 2 个字节大小的 String 的大小会被更改?

c++ - 如何通过模板参数推导避免衰减

c++ - 比可转换类型的循环依赖更好的设计

c++ - 重载子类