jeudi 3 décembre 2020

C++ singleton implementation with splitted declaration and definition of the singleton class

Singleton implementation I have seen use the following code (reference):

// MySingleton.hpp
class MySingleton{
public:
  static MySingleton& getInstance(){
    static MySingleton instance;
    return instance;
  }

private:
  MySingleton()= default;
  ~MySingleton()= default;
  MySingleton(const MySingleton&)= delete;
  MySingleton& operator=(const MySingleton&)= delete;
};

I would like to know if it is possible to split the declaration and the definition of MySingleton like this:

// MySingleton.hpp
class MySingleton{
public:
  static MySingleton& getInstance();

private:
  MySingleton()= default;
  ~MySingleton()= default;
  MySingleton(const MySingleton&)= delete;
  MySingleton& operator=(const MySingleton&)= delete;
};
// MySingleton.cpp
MySingleton& MySingleton::getInstance(){
  static MySingleton instance;
  return instance;
}

Other C++ singleton implementations I have seen use static pointer member variable, so I am wondering if having static MySingleton instance; in the cpp file is still correct?

Aucun commentaire:

Enregistrer un commentaire