Thursday, February 18, 2010

C and C++ Programming - Best practice for Singleton pattern

Best practice for the singleton class to avoid the mis-usage.

1) Make the constructor as private.
2) Hide the copy constructor
3) Hide the = operator
4) Return the reference of the instance instead of pointer in the instance() method

Below is the example:

class Singleton
{

public:

    /*!
     * @brief Method to retrieve the object (singleton pattern)
     */
    static Singleton & instance();

    /*!
     * @brief Destructor
     */
    virtual ~Singleton();

protected:

private:
    /*!
     * @brief constructor, which can only be accessed by instance() method
     */
    Singleton();

    /**
     * @brief Hide the copy constructor.
     */
    Singleton(const Singleton & p_singleton);

    /**
     * @brief Hide the operator '='.
     */
    Singleton & operator =(const Singleton & p_rhs);

    /*!
     * @brief singleton, can only be accessed by instance()
     */
    static Singleton* c_pInstance;
};

No comments:

Post a Comment