c++ - 静态成员错误地初始化为空字符串

标签 c++ initialization static-members

我有三个文件:

api.h:

class HttpApi{
 public:
    static bool postData(string json);

 private:
    static  string remoteHost;
    static  string port;
    static  string url;
};

api.cpp:

string HttpApi::remoteHost = Config::getInstance().getRemoteServer();
string HttpApi::port = Config::getInstance().getPort();
string HttpApi::url="/api/miner";

bool HttpApi::postData(string json)
{
    //Here I print Config::getInstance.getRemoteServer(), the value is correct set here

    cout<<"Start resolve "<< remoteHost<<"   "<<port<<endl;
    cout<<"Succeed in resolving "<<endl;

}

最后:

int main(int argc, char** argv)
{
    Config&  config = Config::getInstance();
    cout<<"Start loading configuration "<<endl;
    config.loadConfig("config.ini");

    HttpApi::postData("hello world");
}

我的问题是remoteHostport这两个成员的初始化是无效的:在运行时,两者都是空的。

这里的 Config 是一个单例类,它从 config.ini 中读取值。它有一些成员,例如remoteHostport

为什么两个静态成员都是空的,我该如何解决?

最佳答案

因为您没有提供 Minimal, Complete, and Verifiable example ,人们只能猜测会发生什么。

首先,类的静态数据成员在程序的最开始以未指定的顺序初始化,然后调用 main()1。这意味着

string HttpApi::remoteHost = Config::getInstance().getRemoteServer();
string HttpApi::port = Config::getInstance().getPort();

之前被评估
config.loadConfig("config.ini");

其次,如果我们假设 Config::getInstance() 在调用任何 loadConfig 之前返回一个默认构造的实例,并且如果我们还假设一个默认构造的实例Config 只是空字符串的集合,那么我们可以肯定地说 HttpApi::remoteHostHttpApi::port 将从空字符串初始化。

最后,一个可能的解决方案是放弃反模式 Singleton is,或者为 HttpApi 定义一种方法来使用已经加载的配置:

void HttpApi::load(Config const& conf) // obviously declared as static
{
    remoteHost = conf.getRemoteServer();
    port       = conf.getPort();
}

int main(int argc, char** argv)
{
    Config& config = Config::getInstance();
    std::cout << "Start loading configuration\n";
    config.loadConfig("config.ini");
    HttpApi::load(config);
    HttpApi::postData("hello world");
}

1) 对于好奇的读者来说,这并不完全正确:

[class.static.data]/6

Static data members are initialized and destroyed exactly like non-local variables ([basic.start.static], [basic.start.dynamic], [basic.start.term]).

[basic.start.dynamic]/4

It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred.

关于c++ - 静态成员错误地初始化为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256451/

相关文章:

C++,从具有引用返回类型的函数返回什么以指示错误

c++ - 如何检查变量是否有资源?

c++ - ZXing 库 : Errors in iOS: private field 'cached_y_' is not used

c# - C#中初始化和赋值有什么区别

c - 数组成员定义为常量

C++类静态变量问题 - C programmer new to C++

c++ - 链表C++实现

c++ - 多次调用初始化函数时的最佳实践?

c++ - C++中的静态成员错误

java - 多线程处理中静态成员的意外行为