c++是否可以延迟常量static成员的初始化?

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

本文关键字:成员 初始化 static 常量 是否 延迟 c++      更新时间:2023-10-16

我正在使用Qt,但这是一个通用的c++问题。我的情况很简单,我有一个类Constants,它有一个常量静态成员,我希望它在某些函数调用后初始化。

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();
}

编译时得到:

QCoreApplication::applicationFilePath:请先实例化QApplication对象

所以这里的问题很明显。当在Constants.cpp中调用QApplication的静态函数时,QApplication还没有被Qt安装。我需要等待直到QApplication a(argc, argv);行在main.cpp

中被传递

这是可能的,如果不是,你有什么建议来克服这个?

谢谢

典型解决方案:

#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
    static const char* const getFILE_NAME();
};
#endif // CONSTANTS_H

#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;
}

一种选择是从函数返回,将其保存在静态变量中。这将在函数第一次被调用时初始化。

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