Singleton: How should it be used

后端 未结 24 2271
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:

So I have read th

24条回答
  •  别那么骄傲
    2020-11-22 05:22

    The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.

    A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.

    Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.

    Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).

    With that in mind, GOAs can be initialised like this:

    namespace {
    
    T1 * pt1 = NULL;
    T2 * pt2 = NULL;
    T3 * pt3 = NULL;
    T4 * pt4 = NULL;
    
    }
    
    int main( int argc, char* argv[])
    {
       T1 t1(args1);
       T2 t2(args2);
       T3 t3(args3);
       T4 t4(args4);
    
       pt1 = &t1;
       pt2 = &t2;
       pt3 = &t3;
       pt4 = &t4;
    
       dostuff();
    
    }
    
    T1& getT1()
    {
       return *pt1;
    }
    
    T2& getT2()
    {
       return *pt2;
    }
    
    T3& getT3()
    {
      return *pt3;
    }
    
    T4& getT4()
    {
      return *pt4;
    }
    

    It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).

    As for when I use singletons? I used them for 2 things - A singleton table that indicates what libraries have been loaded with dlopen - A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.

提交回复
热议问题