Hi Coders,
I was just trying out a simple singleton class. I have wriiten the below code.
Now My que is : How do I instantiate the class from main function. PLS HELP :)

class MOV{
        private:static MOV* inst;
                MOV(){cout<<"Hellooooooo\n"<<endl;}
        public:static MOV* get_it(){
                if(!inst){
                        MOV *p=new MOV;
                        cout<<"1st instance creted..\n"<<endl;
                        return p;
                }
                else {
                        cout<<"Already Instance exists....so Try Agian\n"<<endl;                }
                }
};

int main()
{
        MOV *s;
        MOV *t;
         ???????/* how to cretae instances */
         ???????
         t=MOV::get_it(); /*  complier error*/ 
        return -3;
}

Recommended Answers

All 6 Replies

Your get_it() function should only act as an accessor and you need a static instance of the class not just a pointer.

class A  {
   static A b;
   A () {}
public:
   ~A () {}
   static A Get ( {
      return b;
    }
 };

int main ()  {
   A::Get();
 }

Thanxx....Is it mandatory to Use static functions for a Singleton class.

Best way to make a singleton class will be to implement a singleton template which can hold anyclass and can make any class singleton.

Here is a very simplified version of it:

#include <iostream>
using namespace std;

//A is a simple normal class
class A{
	int x;
public:
	A(): x(2){
	}
	int getX(){
		return x;
	}
};

//This is the Singlton class which hold any class and make any class Singlton
template <typename T>
class Singletone{
	Singletone(){
	}

public:
	static T* _instance;

	static T &Instance(){
		if(!_instance){
			_instance = new T();
			cout<<"1st _instanceance creted..\n"<<endl;
			return *_instance;
		}
		else {
			cout<<"Already Instance exists....so Try Agian\n"<<endl;                }

		return *_instance;
	}
};

template <typename T> T *Singletone<T>::_instance = 0;


//Creating a singleton of A
typedef Singletone<A> ASingleton;


int main()
{
	//we will use ASingleton::Instance() to access the single instance of class A.
	cout << ASingleton::Instance().getX() << endl;

	return 0;
}

Ofcourse above code is a very simple implementation and you can add lots of policies with it (like creation policy, deleting policy, threading policy)

I think you are doing it for learning purpose, hence i am providing you a very simple code.
But If you want to use it for production purpose, then I would suggest to use the boost/loki singleton class.

Is it mandatory to Use static functions for a Singleton class.

It's not mandatory, but that's probably the most common implementation of the Singleton pattern.

But If you want to use it for production purpose

Then I would ask why you think you need a Singleton. In my experience, they're only necessary in some pretty exotic situations. In most other cases, the Singleton pattern is more of a band-aid over design flaws than good design.

>>Is it mandatory to Use static functions for a Singleton class.

I guess you could make a poor implementation of a singleton without a static function, but it is not usual or recommended. Usually the two options are a static function or a free function (non-member function).

The implementation that alwaysLearning0 posted is not only simplified but also generally broken. A more usual and robust implementation is the following:

In singleton.h:

template <typename T>
class singleton_impl {
  private:
    static T& get_instance();
  public:
    operator T&() { return singleton_impl<T>::get_instance(); };
    T& operator*() { return singleton_impl<T>::get_instance(); };
    T* operator->() { return &(singleton_impl<T>::get_instance()); };
    operator T const &() const { return singleton_impl<T>::get_instance(); };
    const T& operator*() const { return singleton_impl<T>::get_instance(); };
    const T& operator->() const { return &(singleton_impl<T>::get_instance()); };

    //usually some additional utility, like operator overloads.
};

In singleton.cpp:

#include "singleton.h"

template <typename T>
T& singleton_impl<T>::get_instance() {
  static T inst;
  return inst;
};

In A.h:

#include "singleton.h"

class A {
  private:
    A(const A&); //non-copyable
    A& operator=(const A&); //non-assignable (note: these two can be done also by inheriting from boost::noncopyable)

    A(); //provide a private default constructor.
  public:
    typedef singleton_impl<A> singleton;
    friend class singleton_impl<A>;

    void print() const;
    //.. whatever implementation of A.
};

Then, in A.cpp:

#include "A.h"

#include "singleton.cpp"

#include <iostream>

template class singleton_impl<A>; //explicit instantiation

A::A() {
  //...
};

void print() const {
  std::cout << "Hello World!" << std::endl;
};

//...

Finally, you can use it as:

#include "A.h"

int main() {
  A::singleton s;
  s->print();
};

The point with the above is that the instance should be a static local variable, should be compiled uniquely (so it should not appear in the header file), and the class should be made non-copyable and only constructible by the singleton class template. The operator overloads are just a convenient way to access the instance. Note also that the A::singleton is a copyable class and acts as a placeholder to access the singleton.


>>they're only necessary in some pretty exotic situations.

Right on! Their implementation is rarely as simple as alwaysLearning0 showed, because they are rarely needed in trivial situations where such a trivial implementation suffices. In the few exotic situations that mandate a singleton, it mandates a true singleton with several precautions taken, beyond the simple precautions I laid out in the code above.

The implementation that alwaysLearning0 posted is not only simplified but also generally broken.

Yea I know, as I was using pointer. But wanted to keep it very simple as so far I understood our original poster's C++ knowledge is not at advanced level and initially he used pointer for his code.
But because it needs lot of other precaution and checking, I made following comment:

Ofcourse above code is a very simple implementation and you can add lots of policies with it (like creation policy, deleting policy, threading policy)

and.. for this:

In the few exotic situations that mandate a singleton, it mandates a true singleton with several precautions taken, beyond the simple precautions I laid out in the code above.

Because of that I said:

I would suggest to use the boost/loki singleton class.

Then I would ask why you think you need a Singleton. In my experience, they're only necessary in some pretty exotic situations. In most other cases, the Singleton pattern is more of a band-aid over design flaws than good design.

There are several examples I could give where you may need singleton solution, on top my head:
1) Lets say you have a server with multiple(could be 1000) Threads handling events, it needs to maintain a transaction sessions among threads to share, you need a single TransactionHandler singleton which will maintain the transaction store.
2) Logger
....
Actually this list could go on and on, IMHO a server can have several components which could be singleton.

Thanks for the feedback though.
I appreciate any feedback anytime.


:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.