Important: Please read the Qt Code of Conduct -

How to initialize a const static member?

  • Hi all - sorry that this is a little long-winded.

    The scenario:

    I've written an app that communicates via a (WiFi) network with various devices via a multicast socket. The app sends messages that include identifiers for the devices (usually a serial number). Every message causes the targeted device to take some action, and send an acknowledgement.

    The problem:

    When I was designing this, it wasn't envisioned that there might be multiple users of the app on the same network. Currently, when a device sends an ack message, it's read by all of the instances of the app. This causes a little confusion.

    The solution:

    The app needs a unique identifier, which it will add to each message. The targeted device will echo the identifier, and the app will filter on this. I was planning on using QUuid for this.

    The glitch:

    How do I create and initialize this QUuid exactly once? It seems that I need a const static member variable in my Message class, but I don't know how to initialize it. I tried declaring it like this:

    class Message
        const static QString m_uuid;

    But where/how do I initialize it? I can't do it in the Message c'tor, because I'll get a new uuid each time. I tried following an example I saw on another forum:

    const QString m_uuid = QUuid::createUuid().toString();
        qDebug() << m_uuid;

    But the compiler gives me an undefined reference error (on the QDebug() line). do I do this?

    If it seems that I'm going about this the wrong way entirely, please tell me.


  • @mzimmers
    If it were useful it would be:

    /*static*/ const QString Message::m_uuid = QUuid::createUuid().toString();

    [My usual untested ;-)] However, before you go any further, I am not sure your initialization expression would be good for a const or static. You are not supposed to call any Qt stuff till after you have created the QApplication, so I'm not sure this is safe here? QUuid may require that, say if it uses any platform calls.

  • @JonB oh, of course...I was missing the class identifier...duh.

    Your proviso notwithstanding, it appears to work: When I start my app, it generates several messages, and they all have identical UUIDs. Thanks!

  • Hopefully this will add to your understanding of what is possible.

  • @Kent-Dorfman thanks for that link. Turns out to be a surprisingly complicated subject, doesn't it? Particularly with the changes to C++ in 11 and 17 (per the article).

    JonB's solution is simple, and seems to work, so I'm probably going to stick with it.

  • This post is deleted!

Log in to reply