Specify construction/destruction order of static locals in different accessors

后端 未结 2 1117
时光取名叫无心
时光取名叫无心 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).

提交回复
热议问题