C++ singleton vs. global static object

前端 未结 8 1429
孤街浪徒
孤街浪徒 2020-11-28 20:06

A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. s

8条回答
  •  臣服心动
    2020-11-28 20:27

    OK, there are two reasons to go with a singleton really. One is the static order thing everyone's talking about.

    The other is to prevent someone from doing something like this when using your code:

    CoolThing blah;
    gs_coolGlobalStaticThing = blah;
    

    or, even worse:

    gs_coolGlobalStaticThing = {};
    

    The encapsulation aspect will protect your instance from idiots and malicious jerks.

提交回复
热议问题