gpt4 book ai didi

c++ - 局部变量的静态初始化

转载 作者:IT老高 更新时间:2023-10-28 23:20:14 25 4
gpt4 key购买 nike

来自 Scott Meyers Effective C++:

if you never call a function emulating a non-local static object, you never incur the cost of constructing and destructing the object, something that can’t be said for true non-local static objects.

功能:

FileSystem& tfs()
{
static FileSystem fs;
return fs;
}

但标准说:

Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope (3.6.2).

这意味着即使我们不调用函数 tfs(),我们也无法确定 fs 变量是否已初始化。因为允许实现对具有静态存储持续时间的变量执行早期初始化。

谁是对的,或者我错过了什么?

最佳答案

Constant initialization描述可以在编译时确定的初始化。

只有在 C++11 及更高版本中,才能考虑具有非平凡构造函数的类型:

if the constructor is constexpr

在“Effective C++”中,Meyers 将您问题中的类按字面意思描述为:

class FileSystem {...};

这意味着如果 C++ 标准是正确的,“有效 C++”也可以保持正确即使在 C++11 之后只要为 FileSystem 提供构造函数不是 constexpr

关于c++ - 局部变量的静态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041515/

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