c++ - 这里保证静态初始化吗?

标签 c++

看这段代码:

struct Foo {
        void *ptr;

        constexpr Foo() : ptr(nullptr) { }
};

Foo f;

是否保证f会被静态初始化?

Clang 在这里使用静态初始化,但是 MSVC doesn't .

最佳答案

是的,标准说 f 将被常量初始化:

[basic.start.init]/2:

A constant initializer for an object o is an expression that is a constant expression, except that it may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types [Note: such a class may have a non-trivial destructor --end note]. Constant initialization is performed:

  • ... [a case for references]

  • if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;

  • ... [a case for objects initialized without a constructor call]

Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

初始化全表达式只是调用Foo的默认构造函数,它是一个常量表达式。

MSVC 发出初始化 f 的代码是错误的。

关于c++ - 这里保证静态初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379738/

相关文章:

c++ - 如何在 Xcode 中包含 .a 库?

c++ - Boost.Log 与 Boost.Log v2

c++ - 只有一列适合其内容大小,而其他列则拉伸(stretch)

c# - 什么是标记接口(interface)?

c++ - 函数的向后兼容性和安全版本

c++ - 从 lambda 捕获中捕获变量会出错?

c++ - 使用 C++ 检测 Windows 体系结构(32 位或 64 位)- wProcessorArchitecture 显示错误的结果

c++ - C++ 中的覆盖和重载

c++ - 解密使用 htpasswd 创建的密码

c++ - 如何组织 python/Boost Python 项目