【问题标题】:Some bugs in singleton mode written in C++用 C++ 编写的单例模式中的一些错误
【发布时间】:2020-12-15 14:36:23
【问题描述】:
#ifndef CONFIG_CPP
#define CONFIG_CPP
#include <mutex>
using namespace std;
class Config {
 public:
  static Config* GetDefult(){
    if (p_instance == nullptr){
      mutex_.lock();
      if (p_instance == nullptr){
        p_instance = new Config();
      }
      mutex_.unlock();
    }
    return p_instance;
  }
 private:
  static Config* p_instance;
  static mutex mutex_;
  Config(){};
};
int main(){
  auto t1 = Config::GetDefult();
}
#endif //CONFIG_CPP

这些消息在我跑步时出现

/tmp/ccKc2m2t.o:在函数Config::GetDefult()': Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0xc): undefined reference to Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x16): 未定义引用Config::mutex_' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x22): undefined reference to Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[ZN6Config9GetDefultEv]+0x43): 未定义引用Config::p_instance' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x48): undefined reference to Config::mutex' Config.cpp:(.text._ZN6Config9GetDefultEv[_ZN6Config9GetDefultEv]+0x54): 未定义对 `Config::p_instance' 的引用 collect2:错误:ld 返回 1 个退出状态

【问题讨论】:

标签: c++


【解决方案1】:

静态数据成员必须在源文件中的类声明之外进行初始化。它们具有全局范围,通常将多线程代码与静态代码混合不是一个好主意。

class Config {
...
};

Config* Config::p_instance = nullptr;

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多