未解析的外部符号“private: static class variable”C++ [重复]

unresolved external symbol "private: static class variable" c++ [duplicate]

提问人:Justin Mathew 提问时间:5/11/2023 最后编辑:Justin Mathew 更新时间:5/11/2023 访问量:167

问:

我在使用静态方法和锁在 c++ 中创建容器时出现错误。我不是 c++ 专家。谁能帮忙找到真正的问题?下面是代码。我正在使用 v14

#include <iostream>
#include <map>
#include <string>
#include <mutex>
#include <shared_mutex>

class obj {};

class pricercache
{
    static  std::shared_mutex entry_mutex;
private:
    static std::map<std::string,obj>& getInstance()
    {
        static std::map<std::string, obj>    engines;
        return engines;
    }
public:

    pricercache(pricercache const&) = delete;
    void operator=(pricercache const&) = delete;

    static obj get(std::string const& key)
    {
        std::shared_lock<std::shared_mutex> lk(pricercache::entry_mutex);
        std::map<std::string, obj>::const_iterator const it =
            getInstance().find(key);        
        return it->second;
    }
    static void add(std::string const& key,
        obj engine)
    {
        std::lock_guard<std::shared_mutex> lk(pricercache::entry_mutex);
        auto& engines = getInstance();
        if (engines.find(key) == engines.end())
            engines.insert(std::make_pair(key, engine));
    }
};

int main()
{
    std::cout << "Hello World!\n";
    obj v1; 
    obj v2;
    pricercache::add("1", v1); 
    pricercache::add("2", v2);

    auto A = pricercache::get("1");
    auto b = pricercache::get("2");

    std::cout << "Done!\n";

    
}

我得到的错误是:

错误 LNK2001:未解析的外部符号“private: static class std::shared_mutex pricercache::entry_mutex”(?entry_mutex@pricercache@@0Vshared_mutex@std@@A)

如果您对容器类有任何其他建议,我也非常欢迎并非常感谢。 提前致谢。

C++ C++14 互斥静态 方法 未解析外部

评论

0赞 Eljay 5/11/2023
你在哪里定义?std::shared_mutex pricercache::entry_mutex;
0赞 Jesper Juhl 5/11/2023
题外话,但你为什么要使用一个 8 年前的 IDE/编译器?
1赞 user4581301 5/11/2023
如果发现密钥存在且未插入,则应通知调用方,以防止将来因调用方对容器的看法与实际情况不同而产生问题。add
0赞 user4581301 5/11/2023
@JesperJuhl可能和我的原因一样:钱!
0赞 Jesper Juhl 5/11/2023
在源文件中看到很奇怪 - 源文件不应该是 d,所以它没有意义。#pragma once#include

答:

0赞 Karen Baghdasaryan 5/11/2023 #1

编译器会抱怨,因为您已声明静态成员,但未定义。在代码中的某个地方,你应该这样定义它

std::shared_mutex pricercache::entry_mutex; // definition of the entry_mutex