以下代码在gcc上导致segfault(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()调用的行被注释时,segfault消失。

最佳答案

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

在这一行上,alog两次引用完全相同的数据成员。叮当警告:



您要查找全局alog-因此可以使用范围解析运算符:
template<> logger<std::ostream>& A<logger<std::ostream>>::alog = ::alog;

live example on wandbox.org

10-08 09:13