在 iostream 中使用静态数据 header

Use of static data inside iostream header

我在 godbolt.org 上玩,注意到编译器添加了一些 "extra code" 'empty main()' 包含 iostream header。

在研究了标准之后,我认为构建和初始化 objects cincoutcerrclogwcinwcoutwcerrwclog,,如果它们还没有 constructed/initialized。

N4606:§ 27.5.3.1.6

27.5.3.1.6 Class ios_base::Init [ios::Init] 

namespace std {
   class ios_base::Init {
      public:
         Init();
         ~Init();
      private:
         static int init_cnt; // exposition only
   };
}

但是对于 static 数据,所有标准表示它计算 class Init 的构造函数和析构函数调用的次数,并初始化为零。

2 For the sake of exposition, the maintained data is presented here as: (2.1) — static int init_cnt, counts the number of constructor and destructor calls for class Init, initialized to zero.

我不明白static int init_cnt;在这里有什么用? 为什么我们需要计算 constructor/destructor 被调用了多少次?

基于https://github.com/maniacbug/StandardCplusplus/blob/master/ios.cpp#L163我认为如果需要 then program at the end when calling destructors for global variables can properly destruct cin, cout, cerr, clog, wcin、wcout、wcerr 和 wclog。

来自 http://www.csci.csusb.edu/dick/c++std/september/lib-iostreams.html :

~Init();

Effects: Destroys an object of class Init. The function subtracts one from the value stored in init_cnt and, if the resulting stored value is one, calls cout.flush(), cerr.flush(), clog.flush(), wcout.flush(), wcerr.flush(), wclog.flush().