Thread-safe static variables without mutexing?

前端 未结 5 1190
无人及你
无人及你 2021-02-19 10:32

I remember reading that static variables declared inside methods is not thread-safe. (See What about the Meyer\'s singleton? as mentioned by Todd Gardner)

Dog* M         


        
5条回答
  •  别跟我提以往
    2021-02-19 11:22

    One way you could do it that does not require a mutex for thread safety is to make the singleton a file static, rather than function static:

    static Dog dog("Lassie");
    Dog* MyClass::BadMethod()
    {
      return &dog;
    }
    

    The Dog instance will be initialised before the main thread runs. File static variables have a famous issue with the initialisation order, but as long as the Dog does not rely on any other statics defined in another translation unit, this should not be of concern.

提交回复
热议问题