I have this:
Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <atomic>
#include <mutex>
class Singleton
{
public:
static std::atomic<Singleton*> Singleton::m_instance;
static std::mutex Singleton::m_mutex;
static Singleton* getInstance();
Singleton();
~Singleton();
};
#endif
Singleton.cpp
#include "Singleton.h"
Singleton::Singleton()
{
}
Singleton* Singleton::getInstance()
{
Singleton* tmp = m_instance.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (tmp == nullptr)
{
std::lock_guard<std::mutex> lock(m_mutex);
tmp = m_instance.load(std::memory_order_relaxed);
if (tmp == nullptr)
{
tmp = new Singleton;
std::atomic_thread_fence(std::memory_order_release);
m_instance.store(tmp, std::memory_order_relaxed);
}
}
return tmp;
}
Singleton::~Singleton() {}
main.cpp
#include "Singleton.h"
#include <iostream>
int main()
{
Singleton* singleton = Singleton::getInstance();
std::cout << "Hello World!" << std::endl;
return 0;
}
当我尝试构建时,我会收到这些错误(Visual Studio):
错误1:error LNK2001: 未解析的外部符号“public: static struct std::atomic Singleton::m_instance”(?m_instance@Singleton@@2U?$atomic@PAVSingleton@@@std@@A) c:...Singleton.obj Singleton
错误2:error LNK2001: 未解析的外部符号“public: static class std::mutex Singleton::m_mutex”(?m_mutex@Singleton@@2Vmutex@std@@A) c:\Users\InusualZ\documents\visual ...Singleton.obj Singleton