Initializing a non-primitive static data type inside a class in C ++

#include <QQueue>
#include <QString>

class   Util {
public:

    static QQueue<QString> links;

    Util() {
    }
};

    Util::links.enqueue("hello world");

How can i do this?

+3
source share
4 answers

You can initialize it with the function:

QQueue<QString> make_links() {
    QQueue<QString> queue;
    queue.enqueue("hello world");
    return queue;
}

QQueue<QString> Util::links = make_links();

I am not familiar with QT, but it is hoped that they will add support for C ++ 11 initialization lists, in which case you can initialize it as:

QQueue<QString> Util::links {"hello world"};

(UPDATE: according to the link in the Shahbaz comment, you can really do this if using C ++ 11).

+2
source

Try using a static member function:

#include <QQueue>
#include <QString>

class   Util {
public:

    static QQueue<QString>& links() {
      static QQueue<QString> instance;
      static bool is_init = false;
      if(!is_init) {
        instance.enqueue("hello world");
        is_init = true;
      }
      return instance;
    }

    Util() {
    }
};

In C ++ 11, QQueue seems to support initializer lists, as Shahbaz said:

QQueue<QString> Util::links = {"hello world"};
+1
source

:

:

#include <QQueue>
#include <QString>

class   Util {
public:

    static QQueue<QString> links;

    Util() {
    }
};

cpp:

namespace {
    struct StaticInitializer {
        StaticInitializer() {
            Util::links.enqueue("hello world");
        }
    } initializer;
}
+1

, , :

QQueue<QString> Util::links;

QQueue<QString> Util::links(1); // with constructor parameters if necessary
0

All Articles