std::cout usage in constructors of objects with st

2019-06-23 22:01发布

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?

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-23 22:29

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;
查看更多
登录 后发表回答