Object initialization

In the book "C ++ Language," the author argued that

Sometimes, when you create a library, it is necessary or just convenient to invent a type with a constructor and a destructor for the sole purpose of initializing and cleaning. This type will be used only once: select a static object so that the constructor and destructor are called.

I am interested in what scenario this operator refers to? Or how does this statement help in software development?

The book also provides an example.

class Zlib_init{ Zlib_init( ); ~Zlib_init( ); }; class Zlib{ static Zlib_init x; } 

And the book says that

Unfortunately, it is not guaranteed that such an object is initialized before its first use and destroyed after its last use in a program consisting of separately compiled units.

Why could this happen?

Thanks for clarifying.

+4
source share
2 answers

The C ++ standard does not specify the order in which static objects are created. Therefore, if you need a hierarchy in static objects, you need them to depend on each other (for example, one must be a member of the other). The design from the book guarantees this behavior.

For example, a hypothetical game engine needs sound and graphics processors to work if you declare them as static objects in separate compilation units and use one of the other, there is no guarantee that this will not work if you do not code them as you indicated.

See C ++ faq for the second part of your question.

+2
source

Unfortunately, it is not guaranteed that such an object is initialized before its first use and destroyed after its last use in a program consisting of separately compiled units.

For example, if you have an instance of your class in the static storage in one module and you want to use it from the constructor of another class in the static storage in another module. In this case, you mean that the first instance will be initialized to the second. But the language does not have the ability to indicate this order if the instances are defined in separate modules.

Sometimes, when you create a library, it is necessary or just convenient to invent a type with a constructor and a destructor for the sole purpose of initializing and cleaning. This type will be used only once: select a static object so that the constructor and destructor are called.

This is useful when you are working with the 3rd part of libs, which requires an initialization and termination call. For example, WinSock 2 requires WSAStartup before you can call other WSA and WSACleanup functions when you are done with WinSock in your process. If you have a static instance of such a class that calls WSAStartup in the constructor and WSACleanup in the destructor, you should be able to use WSA functions in other places in your program (except for the constructors / destructors of other static objects).

0
source

Source: https://habr.com/ru/post/1343957/


All Articles