重载时的分段错误QDebug :: operator<<

时间:2013-11-12 14:48:57

标签: c++ qt segmentation-fault operator-overloading qdebug

我试图为QDebug::operator<<重载std::string。我知道我们可以使用std::string函数调试(使用qDebug())std::string::c_str()个对象,但我想避免每次都输入.c_str

这是我的尝试

#include <QDebug>
#include <string>

inline const QDebug& operator<< (const QDebug& qDebugObj, const std::string& str) {
    return qDebugObj << str.c_str();
}

int main()
{
     std::string s = "4444555";
     qDebug() << s;
}

该程序产生分段错误。这段代码有什么不对?

这是堆栈:

#1  0x00000037c407a911 in malloc () from /lib64/libc.so.6
#2  0x00000037ca8bd09d in operator new(unsigned long) () from /usr/lib64/libstdc++.so.6
#3  0x00000037ca89c3c9 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) ()
   from /usr/lib64/libstdc++.so.6
#4  0x00000037ca89cde5 in ?? () from /usr/lib64/libstdc++.so.6
#5  0x00000037ca89cf33 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) () from /usr/lib64/libstdc++.so.6
#6  0x00000000004012ca in operator<< (qDebugObj=..., str="4444555") at main.cpp:5

2 个答案:

答案 0 :(得分:4)

如果您查看every overloaded output operator,您会看到 none 拥有const限定符。这是你的问题,你试图修改一个常量对象。删除const的{​​{1}}限定条件和返回值。

你应该有编译器警告尖叫它,如果没有,那么你需要启用更多警告(至少在使用GCC / clang编译时使用qDebugObject。)


Mike Seymour在评论中回答的实际问题是,你的重载将被递归调用,直到你得到堆栈溢出。

绕过一种方法可能是将字符串转换为其他内容,例如-Wall

QString

答案 1 :(得分:1)

除了尝试制作输出流const之外,您还没有按照QT documentation

中的说明进行操作
// with the fixed output operator
inline QDebug operator<<(QDebug dbg, const std::string& str)
{
    dbg.nospace() << QString::fromStdString(str);
    return dbg.space();
}

QT希望输出操作符通过副本传递(而不是通过引用)。曾经有过这样的理由,但我不记得它是什么。

相关问题