RE: Singleton instantiated more than once with -fvisibility=hidden

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



There are many ways to implement the Singleton Pattern. Each has their
own positives and negatives. I would advice looking at "Scott Meyers"
book "More Effective C++"
http://www.amazon.co.uk/exec/obidos/ASIN/020163371X/ref=pd_bxgy_text_2_c
p/026-5023597-8506032


Personally I prefer being as simple as possible (Like your original
code).



The only problem with your original code is that 

singleton* singleton::instance()

is defined in the header file. Therefore the implementation of instance
is not in the resulting shared library.

If you move the definition into the file singleton.cc then I believe
(though not tested) that your problem will be resolved.


As a secondary question/comment. Why return a pointer. To me this
implies it can fail and return a NULL (and thus needs to be checked). I
(personally) would return a reference.


singleton.cc

singleton&  singleton::instance()
{
    static singleton   myInstance;
    return(myInstance);
}

There is a small caveat to implementing the singleton this way. The
problem of the singleton being used by another singleton (that is
created before this one) in its destructor. [I'll let you think about
why that is a problem] Solutions to this and other problem are discussed
in "Scott Meyers" book.

PS. Because C++ automatically defines certain methods and to make sure
no other copies of a singleton can be created the following methods
should be defined as private:

class singleton
{
    public:
        singleton& instance();
    private:
         singleton();    // provide definition
        ~singleton();    // provide definition

         /*
          * The following methods should be declared so that the
compiler
          * does not generate default implementations of them.
          * But as they will never be used you do not need to actually
define them.
          */
         singleton(const singleton& copy);            // No definition
required.
         singleton& operator=(const singleton& copy); // No definition
required.
};




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux