C ++ is it possible to delay initialization of a static static member?

I use Qt, but this is a general question in C ++. My case is simple, I have a class Constantsthat has a constant static member that I want it to be initialized after making certain function calls.

Constants.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const FILE_NAME;
};

#endif // CONSTANTS_H

Constants.cpp

#include "constants.h"
#include <QApplication>

const char* const Constants::FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include "constants.h"
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qDebug()<< "name: "<<Constants::FILE_NAME;
    //for those who are unfamiliar with Qt, qDebug just prints out
    return a.exec();
}

When compiling, I got:

QCoreApplication :: applicationFilePath: first instantiate the QApplication object

So, the problem here is obvious. When the static QApplication function is called in Constants.cpp, QApplication has not yet been installed by Qt. I need to somehow wait while in main.cpp

no string will be transmitted QApplication a(argc, argv);

Is it possible, and if not what else could you offer to overcome this?

thank

+5
2

- , . .

char const * const file_name()
{
    // Store the string, NOT the pointer to a temporary string contents
    static std::string const file_name =
        QApplication::applicationFilePath().toStdString();
    return file_name.c_str();
}
+7

:

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const getFILE_NAME();
};

#endif // CONSTANTS_H

cpp

#include "constants.h"
#include <QApplication>

const char* const Constants::getFILE_NAME()
{
    static const char* const s_FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();

    return s_FILE_NAME;
}
+11

All Articles