1

我试图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
4

2 回答 2

4

如果您查看每个重载的输出运算符,您会发现没有一个具有const限定符。这是您的问题,您尝试修改一个常量对象。去掉和返回值的const限定。qDebugObject

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


正如 Mike Seymour 在评论中回答的那样,实际问题是您的重载将被递归调用,直到您获得堆栈溢出为止。

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

return qDebugObj << QString::fromStdString(str);
于 2013-11-12T14:52:40.967 回答
1

除了您尝试制作输出流之外const,您还没有按照QT 文档中的说明进行操作。

// with the fixed output operator
inline QDebug operator<<(QDebug dbg, const std::string& str)
{
    dbg.nospace() << QString::fromStdString(str);
    return dbg.space();
}

QT 希望通过复制(而不是通过引用)传递输出运算符。这曾经是有原因的,但我不记得是什么原因了。

于 2013-11-12T15:00:11.163 回答