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

时间:2018-05-17 11:20:52

标签: c++

以下代码导致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()调用的行被注释时,段错误就会消失。

1 个答案:

答案 0 :(得分:8)

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;

live example on wandbox.org

相关问题