Design of a holder class that will be used to store data at multiple places in the program

Viewed 110

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, singleton or const DataStore& or shared_ptr<DataStore>?
  • Do we need to make it thread-safe even if calling setMember happens 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;?
1 Answers

What is best way to create and share instance of this class, singleton or const DataStore& or shared_ptr<DataStore>?

Access to the class object is always read operation when you choose singleton or shard_ptr.(I cannot understand what const DataStore& means.)

Do we need to make it thread-safe even if calling setMember happens only at once place? What are the possibilities to make it thread-safe? Will the existing code work?

getMember returns const lvalue reference. So that your code doesn't lock anything. copy object or lock data access outside of this class.

You need to ensure that read operation and write operation doesn't occur at same time.

Some of the setters can be called very frequently, do I need to make the member as reference, DataType& _member;?

As already pointed out, you should use std::shared_mutex outside of the class to avoid object copy. this means that you can simply remove the DataStore class because they are no longer needed.

Related