std::cout usage in constructors of objects with static storage duration

我的未来我决定 提交于 2019-12-23 12:55:59

问题


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:


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;


来源:https://stackoverflow.com/questions/37706549/stdcout-usage-in-constructors-of-objects-with-static-storage-duration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!