0

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?

Catree
  • 2,477
  • 1
  • 17
  • 24
  • did you try it? What did you compiler say about it? – 463035818_is_not_an_ai Dec 03 '20 at 10:32
  • Compilation is fine. I am more concerned about the validity of the implementation, especially with specific C++ details like `static` keyword (I am not a C++ expert). – Catree Dec 03 '20 at 10:34
  • I didn't find a good duplicate, but what you have is a Meyers singleton. Search for that term. Having the instance as static local in the method is rather common actually – 463035818_is_not_an_ai Dec 03 '20 at 10:43
  • related: https://stackoverflow.com/questions/1661529/is-meyers-implementation-of-the-singleton-pattern-thread-safe – 463035818_is_not_an_ai Dec 03 '20 at 10:44
  • External definition of class member functions in C++ source (with the declaration in header) is very usual. That the class forms a singleton doesn't change it. To have a `static` instance defined in the C++ source was usual in former times. (With newer C++ standard `static inline` became available which allows the definition of `static` things in the header but the older form is still valid.) – Scheff's Cat Dec 03 '20 at 12:59

0 Answers0