【发布时间】:2011-08-02 22:42:07
【问题描述】:
我有一个我想要的准单例类(准单例在大多数情况下是指作为静态函数的单个对象,但用户也可以构建自己的本地副本以供短期使用)从其析构函数写入 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 块中,以防写入引发异常。) ?
【问题讨论】:
标签: c++