c – 具有静态存储持续时间的对象构造函数中的std :: cout用法

在C 98 / C 03中使用stc :: cout在具有statc存储持续时间的对象的构造函数中是否安全?

从这个answer看来它不是,但它不包括标准的任何引用.

在C 11和C 14中这样做是否安全?

最佳答案 从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使用类似的术语,但没有“as if”子句.

基本上,这个禁止在main之前使用以下内容:

#include <ostream>
extern std::ostream cout;
点赞