c – Meyers Singleton Scope
发布时间:2020-12-16 10:00:32 所属栏目:百科 来源:网络整理
导读:在下面的程序中,似乎Registry Singleton不会在调用静态函数时保持不变.这种方法有什么问题? #include iostream#include string#include unordered_mapusing namespace std;class Test {typedef unordered_mapstring,string Registry;public: static Registr
在下面的程序中,似乎Registry Singleton不会在调用静态函数时保持不变.这种方法有什么问题?
#include <iostream> #include <string> #include <unordered_map> using namespace std; class Test { typedef unordered_map<string,string> Registry; public: static Registry ®istry() { 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; }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |