C++ Segmentation Fault when using cout in static variable initialization

后端 未结 3 1712
攒了一身酷
攒了一身酷 2021-02-19 16:57

I have a program where I use cout to emit debug information. The code is executed in the initialization of a static global variable, i.e. quite early in the program execution. W

相关标签:
3条回答
  • 2021-02-19 17:46

    Static variable initialization is a no-man's-land. You will avoid problems if you avoid doing significant work there. Maybe you should wrap the static variable in a Singleton pattern so you can defer initialization to the first time it's used.

    0 讨论(0)
  • 2021-02-19 17:55

    As Luchian has pointed out, you cannot use std::cout before the first instance of ios_base::Init has been constructed. You don't have to define an instance, however; including <iostream> should be enough.

    Order of initialization is defined within a single translation unit. If you include <iostream> at the top of all files which have static instances, you should be OK. If the constructor of a static object calls a function in another translation unit, however, and the output is in that translation unit, it is not sufficient to include <iostream> only in the translation unit which does the output. You must include it in the translation unit where the static variable(s) are defined. Even if they don't do any output.

    0 讨论(0)
  • 2021-02-19 17:58

    std::cout is an object in static storage. It's guaranteed to be initialized before entering main, but not necessarily before other statics in your code. Seems like the static initialization order fiasco.

    After some digging:

    27.4.2.1.6 Class ios_base::Init

    Init ();

    3) Effects: Constructs an object of class Init. If init_cnt is zero, the function stores the value one in init_- cnt , then constructs and initializes the objects cin, cout, cerr, clog (27.3.1), wcin, wcout, wcerr, and wclog (27.3.2). In any case, the function then adds one to the value stored in init_cnt .

    0 讨论(0)
提交回复
热议问题