Is this guaranteed by the C ++ standard that cin, cout, etc. Will be created first and destroyed last?

cin , cout , related to base streams - is it guaranteed anywhere in the standard that these obejcts will be created first and destroyed last?

This would imply that non-local static objects can rely on them in their constructors and destructors (without spaces between these objects and main threads).

+6
source share
2 answers

They are guaranteed to be created before the declaration of any static object after the inclusion of <iostream> and, in any case, before the start of main . They are not destroyed during program execution.

Inclusion of the header leads to the declaration of a static variable of the ios_base::Init , the creation of which ensures that standard flows will be initialized.

If you want a standard one for this:

C ++ 11 27.4.1 [iostream.objects.overview] / 2: the objects are built, and the associations are set at some point in time before or the first time the object of the ios_base::Init class is built, and in any case before the body of the main one will begin execution. During program execution, objects are not destroyed. The results of including <iostream> in the translation block should be as if <iostream> defined an ios_base::Init instance with a static storage duration. In exactly the same way, the entire program should behave as if there was at least one instance of ios_base::Init with a static storage duration.

+7
source

The simple answer to your question is no. As others have pointed out, there are guarantees for objects defined in translation units including <iostream> , at least if the object is defined after inclusion. But that doesn’t always help: you include <iostream> in the translation unit, which defines the constructor, not necessarily which defines the static variable. Therefore, cases such as the following are possible:

file1.hh

 class X { public: X(); }; 

file1.cc

 #include "file1.hh" #include <iostream> X::X() { std::cout << "Coucou, me voila!" << std::endl; } 

file2.cc

 #include "file1.hh" X anX; 

In this case, it is possible that the anX constructor is called before std::cout .

To be safe: if the constructor of the object, which can be used as a static variable, wants to use any of the standard threads, this should probably declare a local static type ios_base::Init :

 X::X() { static ios_base::Init dummyForInitialization; std::cout << "Coucou, me voila!" << std::endl; } 

If std::cout has not yet been constructed when this constructor is called, when the static variable is built.

+7
source

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


All Articles