4

Is it safe to use std::cout in constructors of objects with statc storage duration in C++98 / C++03?

It seems from this answer that it isn't but it doesn't include any quotes from the standard.

Is it only safe to do that in C++11 and C++14?

Community
  • 1
  • 1
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

2

From C++14 (N3797), §27.4p2:

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 exe- cution.295 The objects are not destroyed during program execution.296 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.

C++98 uses similar terminology, but without the "as if" clause.

Basically, what this forbids is using the following before main:

#include <ostream>
extern std::ostream cout;
o11c
  • 15,265
  • 4
  • 50
  • 75
  • And what about C++98 / C++03? – FrozenHeart Jun 08 '16 at 15:27
  • So it has the same behavior in all C++ standards and I'm perfectly safe to use `std::cout` in such objects, right? – FrozenHeart Jun 08 '16 at 15:32
  • 3
    There's a chain of DRs, starting from [LWG 369](http://wg21.link/LWG369), and ending at [LWG1123](http://wg21.link/LWG1123) that changed this between C++98 and C++11. While this might be fine in practice, claiming that the standard text in C++98 and C++03 supports this is misleading at best. – T.C. Jun 08 '16 at 15:47
  • 5
    And the code claimed to be forbidden by this paragraph (assuming that you actually meant to put `cout` in `std`) is in fact already forbidden by the rule that you can't add declarations to `std` unless otherwise specified. – T.C. Jun 08 '16 at 15:50
  • @T.C. As if that ever stopped anybody. – o11c Jun 08 '16 at 22:26