Singleton pattern in C++

前端 未结 8 1821
北荒
北荒 2020-11-30 18:10

I have a question about the singleton pattern.

I saw two cases concerning the static member in the singleton class.

First it is an object, like this

8条回答
  •  Happy的楠姐
    2020-11-30 18:28

    The difference is that the second one leaks memory (the singleton itself) while the first one does not. Static objects are initialized once the first time their associated method is called, and (so long as the program exits cleanly) they are destroyed before the program exits. The version with the pointer will leave the pointer allocated at program exit and memory checkers like Valgrind will complain.

    Also, what's stopping somebody from doing delete GlobalClass::instance();?

    For the above two reasons, the version using the static is the more common method and the one prescribed in the original Design Patterns book.

提交回复
热议问题