0

I'm confused about the singleton pattern. To my understanding,

  • It is a class that allows only one object to be created from it.
  • To do this, the constructor, copy constructor, and assignment operator overloading function are made private to prevent any other objects from being created.
  • The one and only instance is made public in the class and is static. Its default value is NULL.
  • A function, usually called getInstance() or something similar, is used to allocate memory for the static object if it hasn't been done already

So my question is what do the constructors and copy constructor and &operator=() functions look like? Also will the destructor be public or private?

class Database { private: Database() { //??? } Database(const Database &db) { //??? } Database &operator=(const Database &db) { //??? } //~Database() {...} public: static Database database = NULL; Database &getDB() { if (database == NULL) { database = new Database(); return database; } return database; } ~Database() {...} } 
4
  • The constructor is just like any normal constructor, it does any needed initialisation / resource gathering. Copy constructor and assignment are empty, a singleton should/can not be copied anyway. By making them private or deleting them you make sure no-one can use them. Commented Apr 16, 2016 at 18:15
  • Ok. Thanks. What about the destructor? Commented Apr 16, 2016 at 18:19
  • @thisisalongdisplayname Destructor calls for singletons are implementation defined. If you have one for your example using new, you'll need to provide another static function destruct() and call it whenever your program ends. Commented Apr 16, 2016 at 18:42
  • Oh. And should it be public or private? Thanks again Commented Apr 16, 2016 at 19:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.