C++ singleton vs. global static object

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

    In C++, the order of instantiation of static objects in different compilation units is undefined. Thus it's possible for one global to reference another which is not constructed, blowing up your program. The singleton pattern removes this problem by tying construction to a static member function or free function.

    There's a decent summary here.

提交回复
热议问题