C++ Nifty Counter idiom; why?

后端 未结 4 611

I recently came across the Nifty Counter Idiom. My understanding is that this is used to implement globals in the standard library like cout, cerr, etc. Since the experts have c

4条回答
  •  不要未来只要你来
    2021-01-31 09:34

    All of your questions about utility / performance of Nifty Counter aka Schwartz Counter were basically answered by Maxim Egorushkin in this answer (but see also the comment threads).

    Global variables in modern C++

    The main issue is that there is a trade-off taking place. When you use Nifty Counter your program startup time is a bit slower (in large projects), since all these counters have to run before anything can happen. That doesn't happen in Meyer's singleton.

    However, in the Meyer's singleton, every time you want to access the global object, you have to check if it's null, or, the compiler emits code that checks if the static variable was already constructed before any access is attempted. In the Nifty Counter, you have your pointer already and you just fire away, since you can assume the init happened at startup time.

    So, Nifty Counter vs. Meyer's singleton is basically a trade-off between program startup time and run-time.

提交回复
热议问题