当跟踪被禁用时,我们需要抑制qDebug()消息。我知道我们正在使用qInstallMessageHandler(),但我们还需要一个额外的trace方法。
class MyDebug : public QDebug {
public:
explicit MyDebug();
MyDebug(const QDebug &o);
MyDebug(const MyDebug &o);
private:
std::shared_ptr<QString> null_string;
static void doDeleteLater(QString *obj);
};
MyDebug::MyDebug()
: null_string(new QString(), &MyDebug::doDeleteLater), QDebug(null_string.get()) {
qCritical("construct");
}
void MyDebug::doDeleteLater(QString *obj) {
qCritical("delete");
}
MyDebug::MyDebug(const QDebug &o)
: QDebug(o) {
qCritical("called1");
}
MyDebug::MyDebug(const MyDebug &o)
: null_string(o.null_string), QDebug(null_string.get()) {
qCritical("called2");
}
MyDebug Application::trace(const uchar verbosity) const {
MyDebug d = this->logLevel > 6 ? MyDebug(qDebug()) : MyDebug();
// QDebug default verbosity is 2 - Range 0-7
d.setVerbosity(qMin((uchar)7, verbosity));
return d;
}现在使用Application::trace()会导致错误
Application::trace() << QString("test");
...
construct
QTextStream: No device
delete我认为这与复制MyDebug时null_string的生命周期有关,但复制构造函数从未调用过。
使用堆构造的QString*作为QDebug设备是可行的。
发布于 2021-08-26 11:21:55
安装自定义处理程序,如下所示:
#include <QtGlobal>
QtMessageHandler DEFAULT_MSG_HANDLER = 0;
void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
if (type == QtDebugMsg) {
// Ignores debug.
return;
}
// Redirects anything else to the default handler.
(*DEFAULT_MSG_HANDLER)(type, context, msg);
}
int main(int argc, char **argv)
{
DEFAULT_MSG_HANDLER = qInstallMessageHandler(myMessageHandler);
QApplication app(argc, argv);
// ...
return app.exec();
}https://stackoverflow.com/questions/68936491
复制相似问题