gpt4 book ai didi

c++ - std::mutex 和 std::atomic 的链接问题

转载 作者:太空狗 更新时间:2023-10-29 21:19:29 26 4
gpt4 key购买 nike

<分区>

我有这个:

单例.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

单例.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() {}

主要.cpp

#include "Singleton.h"
#include <iostream>
int main()
{
Singleton* singleton = Singleton::getInstance();
std::cout << "Hello World!" << std::endl;
return 0;
}

当我尝试构建时出现此错误(Visual Studios):

Error 1 error LNK2001: unresolved external symbol "public: static struct std::atomic Singleton::m_instance" (?m_instance@Singleton@@2U?$atomic@PAVSingleton@@@std@@A) c:...Singleton.obj Singleton

和:

Error 2 error LNK2001: unresolved external symbol "public: static class std::mutex Singleton::m_mutex" (?m_mutex@Singleton@@2Vmutex@std@@A) c:\Users\InusualZ\documents\visual ...Singleton.obj Singleton

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com