gpt4 book ai didi

c++ - cout 是否保证在静态去初始化期间可用?

转载 作者:可可西里 更新时间:2023-11-01 16:02:48 26 4
gpt4 key购买 nike

我有一个准单例类(准单例在大多数情况下指的是单个对象是一个静态函数,但用户也可以构建自己的本地拷贝以供短期使用)我想要从其析构函数写入 cout,并想知道 cout 是否保证在程序终止后的静态去初始化阶段可用。来自 this question似乎答案是肯定的(函数静态初始化对象的析构函数应该从它们构造时的相反顺序调用,这应该是在 cout 设置之后),但我想检查一下。

// Count calls to a logging function from some point in our code, to determine
// how many times it gets executed during a run, then report calls at the end
// of the program. A quick-and-dirty way of determining how often we execute
// code.
class callCounter;
class callCounter {
public:
callCounter() : has_calls_(false), counts_() {}
~callCounter () {report(std::cout);}
void logCall(const std::string callSite);
void report(std::ostream &os);
void reset();
static callCounter *theCounter();
private:
typedef std::map<std::string, callCount> COUNTMAP;
bool has_calls_;
COUNTMAP counts_;
};

callCounter *callCounter::theCounter()
{
static callCounter theCounts;
return &theCounts;
}

典型的用法是:

callCounter::theCounter()->logCall("foo");

那么在析构函数中使用 cout 是否保证安全(至少就使用 cout 本身而言 - 可以说是绝对安全,我应该将报告包装在 try block 中以防写入引发异常。) ?

最佳答案

简短回答:是

长答案:是的

标准库使用一些技巧来确保 std::cout(和 std::cin/std:cerr)在任何其他对象之前可用(但您必须在翻译单位)。因为它们首先被创建(销毁规则保证的相反顺序)它们在您的对象之后被销毁

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

27.4 标准 iostream 对象

第 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 <iostream> 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.

添加了突出显示。

来自 n1804(基本上是 2003 标准:Pub:2005-04-27)

27.3 标准 iostream 对象

第 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.

不幸的是,可以保证它的部分在脚注中(这是非规范的(即它不能保证实现者应该尝试和实现什么)。

附注:

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

关于c++ - cout 是否保证在静态去初始化期间可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com