引用 std::cout 会导致段错误

Reference to std::cout results in segfault

本文关键字:错误 段错误 std cout 引用      更新时间:2023-10-16

以下代码导致 gcc (Debian 6.3.0-18+deb9u1( 6.3.0 上的段错误20170516

#include <iostream>
template<typename LogT> class logger {
public:
logger(LogT& log) : log_(log) {}
template<typename T> LogT& operator<<(T const& t) {return log_ << "n> " << t;}
private:
LogT& log_;
};
template<typename LogT> class A {
public:
void f() {
alog << "world";
}
static LogT& alog;
};
logger<std::ostream> alog(std::cout);
template<> logger<std::ostream>& A<logger<std::ostream>>::alog = alog;

int main() {
alog << "hello";
A<logger<std::ostream>>().f();
return 0;
}

为什么会这样? 当带有 f(( 调用的行被注释时,段错误消失。

template<> logger<std::ostream>& A<logger<std::ostream>>::alog = alog;

在此行上,alog两次引用完全相同的数据成员。Clang对此警告道:

警告:引用 'alog' 在其自己的初始化中使用时尚未绑定到值 [-Wuninitialized]

您希望查找全局alog- 因此可以使用范围解析运算符

template<> logger<std::ostream>& A<logger<std::ostream>>::alog = ::alog;

wandbox.org 上的现场示例