简体   繁体   English

静态初始化局部变量

[英]Static initialization of local variables

From Scott Meyers Effective C++ : 来自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. 如果你从不调用模拟非本地静态对象的函数,那么你永远不会产生构造和破坏对象的成本,这对于真正的非本地静态对象来说是不可能的。

The function: 功能:

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

But the Standard said: 但标准说:

Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. 具有静态存储持续时间的块范围实体的常量初始化(3.6.2)(如果适用)在首次输入块之前执行。 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). 允许实现 在静态或线程 存储持续时间 执行 其他块范围变量的 早期 初始化, 条件是 允许 实现 在命名空间范围内 静态初始化具有静态或线程 存储持续时间 的变量 (3.6.2)。

That means that we can't say for sure if the fs variable is or is not initialized even if we don't call to the function tfs() . 这意味着即使我们不调用函数tfs() ,我们也无法确定fs变量是否初始化。 Because implementation is permitted to perform early initialization as for variables with static storage duration. 因为允许实现对具有静态存储持续时间的变量执行早期初始化。

Who was right or what did I miss? 谁是对的或我错过了什么?

Constant initialization describes initialization that can be determined at compile-time. 常量初始化描述了可在编译时确定的初始化。

Only in C++11 and later can a type with a non-trivial constructor be considered: 只有在C ++ 11及更高版本中才能考虑具有非平凡构造函数的类型:

if the constructor is constexpr 如果构造函数是constexpr

In "Effective C++", Meyers describes the class in your question literally as: 在“Effective C ++”中,Meyers将您问题中的课程字面描述为:

class FileSystem {...};

This would imply that given the C++ Standard being correct, "Effective C++" can also remain correct even after C++11 as long as the supplied constructor for FileSystem is not constexpr . 这意味着,鉴于C ++标准是正确的,只要提供的FileSystem构造函数不是constexpr ,“Effective C ++” 即使在 C ++ 11 之后也可以保持正确。

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

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