Is cout guaranteed available during static deinitialization?

前端 未结 1 1516
旧时难觅i
旧时难觅i 2021-02-20 14:54

I\'ve got a quasi-singleton class (quasi-singleton in that most use refers to a single object that is a function static, but users can also construct their own local copy for sh

1条回答
  •  误落风尘
    2021-02-20 15:00

    Short Answer: Yes

    Long Answer: Yes

    There are a couple of tricks that the standard library uses to make sure that std::cout (and std::cin/std:cerr) are available before any other objects (But you must #include in the translation unit). Because they are created first (the reverse order of destruction rule guarantees) they are destroyed after your objects.

    See: n3242 (Practically the C++0x standard Pub: 2011-02-28)

    27.4 Standard iostream objects

    Paragraph 2

    The objects are constructed and the associations are established at some time prior to or during the first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution. The objects are not destroyed during program execution. The results of including in a translation unit shall be as if defined an instance of ios_base::Init with static storage duration. Similarly, the entire program shall behave as if there were at least one instance of ios_base::Init with static storage duration.

    Added highlighting.

    From n1804 (which is basically the 2003 standard: Pub: 2005-04-27)

    27.3 Standard iostream objects

    Paragraph 2

    Mixing operations on corresponding wide- and narrow-character streams follows the same semantics as mixing such operations on FILEs, as specified in Amendment 1 of the ISO C standard. The objects are constructed, and the associations are established at some time prior to or during first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution. The objects are not destroyed during program execution280.

    Unfortunately the bit that would make it a guarantee is in the footnotes (which are non-normative (ie its not guaranteed just what the implementer should try and achieve).

    With the footnotes:

    280) Constructors and destructors for static objects can access these objects to read input from stdin or write output to stdout or stderr.

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