Specify construction/destruction order of static locals in different accessors

后端 未结 2 1118
时光取名叫无心
时光取名叫无心 2021-01-23 05:45

I\'m experiencing a crash in cxa_finalize running a program (this is a program, and not a library within):

$ ./ac-test.exe 
Assertion failed: AcLock         


        
相关标签:
2条回答
  • 2021-01-23 06:12

    This is a classical problem when using the Meyers singleton (which is basically what you're doing). The solution is to not destruct the singleton; instead of a static local variable, you should use dynamic allocation without a delete:

    static  AcLogger& GetLogger()
    {
        static AcLogger* logger = new AcLogger;
        return *logger;
    }
    

    Note that in this case, you will have to ensure that each use of the logger flushes (but this is usually the case anyway); otherwise, you may end up with unflushed data.

    With regards to your attempt to use an extended feature of your compiler: I'm not too familiar with it, but I don't see how you can use something called init_priority on a local variable. The construction (and destruction) time of local static variables is defined by the language (and in this case, the destruction time is not what you want). If you want to use this non-standard extension, you'll probably have to make the instance variable a static class member, or maybe even a global (in which case, you can't make the constructor private).

    0 讨论(0)
  • 2021-01-23 06:26

    Assuming the dependency is non-cyclical, you can just leverage the standard behavior of initialization in the order of code flow entry into the function and destruction in reverse order of initialization.

    In other words, have a call to GetLogger() to initialize the logger and then GetAcceptSockets() to initialize the list. This will result in the socket list getting destructed first (while the logger still exists) and then the logger getting destructed last.

    0 讨论(0)
提交回复
热议问题