2

I have a problem with QLoggingCategory(const char * category).

When I use it like:

QString rt = "3";
QString sv = "P";
QLoggingCategory dailyLogger(QString(rt+sv+"Logger").toStdString().c_str());

it doesn't work (my custom message handler doesn't recognize this category).

But when I use:

QLoggingCategory dailyLogger("3PLogger");

message handler sees the category.

Here's the handler function:

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    if (QString(context.category).contains("3"))
    {
        //some code
    }
}

Why does my computed category name not work?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
lazare
  • 31
  • 3
  • 2
    Possible, because `QString(rt+sv+"Logger").toStdString().c_str()` - is a rvalue and it will be invalid at next code line. – Dmitry Sazonov Oct 15 '15 at 09:13

1 Answers1

2

QLoggingCategory retains a copy of the char* pointer with which it's constructed. The pointed-to characters must remain valid and constant for the life of the QLoggingCategory instance.

In your failing example, c_str() returns a temporary which is no longer valid after the std::string goes out of scope. So the QLoggingCategory is now pointing at invalid memory (giving you Undefined Behaviour).

In your second example, you pass a string literal, which is valid for the lifetime of the program, so no lifetime issues arise.

You will need to copy the string data into a char array with a lifetime that outlives the logging category.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103