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?
It is mandatory to initialize the static variable using the static keyword in C else it will return an error. The static variable is only initialized the first time when a function is called. In a static variable, the memory of a static variable is allocated.
A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
Local Variables Declarations specify the type followed by the name, and optionally the initialization. Initialization sets the variable to a new instance. It must be to a type that is compatible with the declaration type. In the above code, the variable a is declared as a string and is initialized to "Hello World".
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With