gpt4 book ai didi

c++ - 迈耶斯单例范围

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

在下面的程序中,注册表单例似乎没有在对静态函数的调用中保持不变。这种方法有什么问题?

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

class Test {
typedef unordered_map<string,string> Registry;
public:
static Registry &registry() {
static Registry reg;
return reg;
}

static void put(string key, string val) {
Registry reg = Test::registry();
reg[key] = val;
}

static string get(string key) {
Registry reg = Test::registry();
return reg[key];
}
};

int main() {
Test::put("a", "apple");
Test::put("b", "banana");
cout << Test::get("a") << endl;
cout << Test::get("b") << endl;
return 0;
}

最佳答案

您正确地返回了对您的单例的引用,但是当您使用它时,您正在获取一个拷贝。违规行如下:

Registry reg = Test::registry();

要解决此问题,请将其修改为:

Registry & reg = Test::registry();

为防止这种情况发生,您可以通过删除复制构造函数和赋值运算符来阻止编译器允许复制:

class Registry : public unordered_map<string,string>
{
public:
Registry() {}
Registry( const Registry & ) = delete;
Registry & operator=( const Registry & ) = delete;
};

关于c++ - 迈耶斯单例范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168446/

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