C++ singleton vs. global static object

前端 未结 8 1432
孤街浪徒
孤街浪徒 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:40

    Another benefit of the Singleton over the global static object is that because the constructor is private, there is a very clear, compiler enforced directive saying "There can only be one".

    In comparison, with the global static object, there will be nothing stopping a developer writing code that creates an additional instance of this object.

    The benefit of the extra constraint is that you have a guarantee as to how the object will be used.

提交回复
热议问题