c++ - 重载 QDebug::operator<< 时出现段错误

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

我试图重载 QDebug::operator<<对于 std::string .我知道我们可以调试(使用 qDebug())std::string使用其 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

最佳答案

如果你看every overloaded output operator ,您会看到 none 具有 const 限定符。这是你的问题,你尝试修改一个常量对象。删除 qDebugObject 和返回值的 const 限定。

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


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

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

return qDebugObj << QString::fromStdString(str);

关于c++ - 重载 QDebug::operator<< 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932314/

相关文章:

c++ - 自由函数和继承

qt 信号/槽和 pthreads 不能很好地协同工作

c - 为什么我会遇到段错误(多维数组 C)

c++ - 从 ARM 的源代码交叉编译 Qt 4.7 的问题

c++ - 成功打印超出范围的字符串索引

c++ - 在 GCC 而不是 Clang 中编写 SIGSEGV 代码

java - Eclipse 是否必须处理 C++ ABI 兼容性问题?

C++:如何将 vector 中包含的对象插入集合中?

c++ - 避免对模板化类方法进行隐式转换

c++ - 在 C++ (Qt) 中设置具有非本地 IP 地址的服务器