简体   繁体   中英

Static initialization of local variables

From 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. 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).

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() . 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:

if the constructor is constexpr

In "Effective C++", Meyers describes the class in your question literally as:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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