引用 std::cout 会导致段错误
Reference to std::cout results in segfault
以下代码导致 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 上的现场示例
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?