| | |
| | | { |
| | | static std::string ObjName(const std::string &name) { return "obj" + name; } |
| | | |
| | | protected: |
| | | public: |
| | | typedef T Data; |
| | | typedef SharedMemory ShmType; |
| | | |
| | | private: |
| | | ShmType &shm_; |
| | | std::string name_; |
| | | Data *pdata_ = nullptr; |
| | | |
| | | bool IsOk() const { return pdata_; } |
| | | |
| | | protected: |
| | | ShmType &shm() const { return shm_; } |
| | | |
| | | public: |
| | | template <class... Params> |
| | | ShmObject(ShmType &segment, const std::string &name, Params &&...t) : |
| | | shm_(segment), name_(name) |
| | | { |
| | | pdata_ = shm_.Create<Data>(ObjName(name_), std::forward<decltype(t)>(t)...); |
| | | pdata_ = shm_.FindOrCreate<Data>(ObjName(name_), std::forward<decltype(t)>(t)...); |
| | | if (!IsOk()) { |
| | | throw("Error: Not enough memory, can not allocate \"" + name_ + "\""); |
| | | } |
| | | } |
| | | template <class... Params> |
| | | ShmObject(ShmType &segment, const bool create_or_else_find, const std::string &name, Params &&...t) : |
| | | shm_(segment), name_(name) |
| | | { |
| | | if (create_or_else_find) { |
| | | pdata_ = shm_.Create<Data>(ObjName(name_), std::forward<decltype(t)>(t)...); |
| | | } else { |
| | | pdata_ = shm_.Find<Data>(ObjName(name_)); |
| | | } |
| | | } |
| | | bool IsOk() const { return pdata_; } |
| | | |
| | | static bool Remove(SharedMemory &shm, const std::string &name) { return shm.destroy<Data>(ObjName(name).c_str()); } |
| | | static Data *Find(SharedMemory &shm, const std::string &name) { return shm.Find<Data>(ObjName(name)); } |
| | | Data *Find(const std::string &name) { return Find(shm_, ObjName(name)); } |
| | |
| | | Data *operator->() { return data(); } |
| | | const Data *operator->() const { return data(); } |
| | | bool Remove() { return Remove(shm_, name_); } |
| | | |
| | | private: |
| | | ShmType &shm_; |
| | | std::string name_; |
| | | Data *pdata_ = nullptr; |
| | | }; |
| | | |
| | | } // namespace bhome_shm |