qDebug输出换行的原因

qDebug()常用的一种方式如下:

qDebug() << 1 << 2 << 3;
qDebug() << 4 << 5 << 6;

输出结果为:

1 2 3
4 5 6

请注意,1、2和3之间都有空格,1、2、3和4、5、6之间换行了。

为何会加入空格?

查看QDebug源码,发现每个operator<<后都有maybeSpace()函数调用,而它会按照space标志加入空格,如下:

1 inline QDebug &operator<<(signed int t) { stream->ts << t; return maybeSpace(); }
2 
3 inline QDebug &maybeSpace() { if (stream->space) stream->ts << ' '; return *this; }

因此,空格可以使用nospace去掉。

为何会换行?

分析一下发现,每次执行完一行输出就换行,猜测是析构时做了手脚,因为operator<<返回的是QDebug&。查看源码发现:

1         if (stream->message_output) {
2             qt_message_output(stream->type,
3                               stream->context,
4                               stream->buffer);
5         }

在qlogging.cpp中查看qt_message_output函数,发现调用

qt_message_print(msgType, context, message);

再查看它的代码,发现:

fprintf(stderr, "%s\n", message.toLocal8Bit().constData());

这就解释了为什么会换行。另外,注意该函数中,上面还有一个处理messageHandler的分支,可以通过它来改变这个输出规则。

posted @ 2021-11-05 16:07  soso101  阅读(1448)  评论(0)    收藏  举报