mercredi 19 décembre 2018

Is it possible to ensure that a function is only called during the 'static initialization' step

I was wondering if it is possible to ensure that a function is only called during the static initialization step of a program?

As an example, say that I have some singleton class that contains a std::map object and exposes the insert and at methods of it. I would like to ensure that reading data from it (the at method) is thread-safe which, to my understanding, requires ensuring that nothing is modifying the data (i.e. using the insert method).

The map is intended to be filled only during static initialization, at which time I'm assuming there is only one thread. Is there any way that I can ensure no misguided user calls insert once main() has begun?


Example code

#include <map>
#include <string>

class Singleton {
  private:
    std::map<std::string, std::string> m_map;
  public:
    static Singleton& instance() {
      static Singleton theSingleton;
      return theSingleton;
    }
    static bool insert(const std::string& key, const std::string& value) {
      return instance().m_map.insert(std::make_pair(key, value) ).second;
    }
    static std::string at(const std::string& key) {
      return instance().m_map.at(key);
    }
};

static bool inserted = Singleton::insert("Hello", "World"); // fine

bool addItem(const std::string& key, const std::string& value) {
  return Singleton::insert(key, value); // not OK
}


Needless(?) to say the actual code is a good deal more complex than this simple example.

Aucun commentaire:

Enregistrer un commentaire