hjk41的日志

Avatar

Effective C++ 47: Ensure that non-local static objects are initialized before they are used

Consider the following code:


// file theFileSystem.cpp
FileSystem theFileSystem;
...

// file Directory.cpp
class Directory{
    public:
    Directory(){
        ...   // use theFileSystem to create a directory
    };
    ...
};

// file main.cpp
Directory dir;


There is a problem with this code: initilization of dir requires theFileSystem to be initialized first, but we don't know the initialization order of the objects, and C++ offers no means to set the order.
The answer is to use static functions that returns reference to static objects instead of non-local static members. For the code above, you can write this:


//file theFileSystem.cpp
FileSystem & theFileSystem{
    static FileSystem fileSystem;
    return fileSystem;
}

// file Directory.cpp
...  // same as above


This solves the problem. Static objects in functions are initiated the first time the functions are invoked. So when we declare dir, the constructor of Directory will call the functions theFileSystem(), in which theFileSystem is constructed and returned. Another advantage of this approach is that if you do not use theFileSystem, then the static variable fileSystem will never be constructed.

评论已关闭