C++ static list with private constructor -


i apologize if has been asked, i'm not sure how 1 best words , couldn't find it.

i have class want maintain map of itself, , list should have instantiations of object.

using std::unordered_map; class myclass {     ~myclass() {};     myclass() {};   // these contain code operate on classes data     static unordered_map<uint32, myclass> list; public:     static const myclass& getobject(uint32 key) {return list[key];};  }; 

when compile code gives me bunch of errors stl saying it's calling deleted functions , such, makes sense because unordered_map uses constructor , destructor, declared unordered_map friend

friend class unordered_map<uint32, myclass>; 

however there doesn't seem fewer errors, speculate due classes used unordered_map pair, , hash. question if there alternative this. should declare more things friends appear giving errors in compiler, or there method?

update: t.c. kindly pointed out couple things i'd overlooked, answer's done complete about-face....

#include <iostream> #include <unordered_map> #include <map> #include <cinttypes>  class myclass {     typedef std::unordered_map<uint32_t, myclass> instances;     friend instances;     friend std::pair<uint32_t, myclass>;     friend std::pair<const uint32_t, myclass>;   public:     static const myclass& getobject(uint32_t key) { return instances_[key] = 2 * key; }     ~myclass() {}     int n() const { return n_; }   private:     myclass() : n_(-1) { }     myclass& operator=(int n) { n_ = n; return *this; }     int n_;     static instances instances_; };  myclass::instances myclass::instances_;  int main() {     const myclass& m20 = myclass::getobject(20);     const myclass& m21 = myclass::getobject(21);     std::cout << m20.n() << ' ' << m21.n() << '\n'; } 

above code at ideone.com.

as per comments, list of necessary friendship isn't documented standard, break new compiler versions or when porting compiler.

alterantively, can store (smart) pointers in unordered_map.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -