I am trying to design a class that works as a data holder (contains lot of members, getters and setters). This class shall be used at multiple other threads in the program and can be used for data exchange, i.e. one component updates the object and others can read out the changed values when needed.
Even if write of a member (by calling setter) can happen only at once place, however getter can be called at multiple places.
Below is the class code.
#include <mutex>
class DataType{};
class DataStore
{
private:
mutable std::mutex _mtx;
DataType _member;
// different other member!
public:
DataStore(): _member(){}
~DataStore(){}
// setters can be called from many places!
void setMember(const DataType& val)
{
std::lock_guard<std::mutex> lock(_mtx);
_member = val;
}
// getters can be called from many places!
const DataType& getMember() const
{
std::lock_guard<std::mutex> lock(_mtx);
return member;
}
};
Questions:
- What is best way to create and share instance of this class,
singletonorconst DataStore&orshared_ptr<DataStore>? - Do we need to make it thread-safe even if calling
setMemberhappens only at once place? What are the possibilities to make it thread-safe? Will the existing code work? - Some of the setters can be called very frequently, do I need to make the member as reference,
DataType& _member;?