why do books/articles prefer implementation#1 over implementation#2?
Because most articles describing the Singleton anti-pattern don't fully understand all the hidden dangers when trying to implement it safely in C++. It's surprisingly difficult to get it right.
What is the actual advantage of using pointer in implementation of Singleton class vs using a static object?
Using a pointer, with new
but no delete
, ensures that the object will never be destroyed, so there is no danger of accessing it after its lifetime has ended. Combined with the "lazy" creation, the first time that it's accessed, this guarantees that all accesses are to a valid object. The disadvantages are that creation is not thread-safe, and that the object and any resources it acquires are not released at the end of the program.
Using a local static object, creation is thread-safe on any compiler that supports the C++11 threading model; also, the object will be destroyed at the end of the program. However, it is possible to access the object after its destruction (e.g. from the destructor of another static object), which could lead to nasty bugs.
The best option is to avoid static data, and globally-accessible data, as much as possible. In particular, never use the Singleton anti-pattern; it combines global, static data with weird instantiation restrictions that make testing unnecessarily difficult.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…