gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:20:03 24 4
gpt4 key购买 nike

我试图重载 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com