Reputation: 2596
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?
Upvotes: 12
Views: 970
Reputation: 63704
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
.
Upvotes: 7