Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can everything in a singleton be static?

In C++, can all the members in a singleton be static, or as much as possible? My thought is, there is only one instance globally anyway.

While searching I did find a lot of discussions on static class in C#, but not familiar about that. Would like to learn about it too.

Whatever thought you have, please comment.

like image 298
Derek Avatar asked Sep 10 '25 10:09

Derek


2 Answers

With a static singleton you can't control when the single will be allocated and constructed. This puts you at the mercy of the c++ order of construction rules for static variables, so if you happen to call this single during the construction of another static variable, the single may not exist yet.

If you have no intentions of ever calling the singleton from the constructor of another static variable, and do not wish to delay construction for any reason, using a static variable for singleton is fine.

See Static variables initialisation order for more info.

like image 77
goji Avatar answered Sep 13 '25 01:09

goji


The singleton pattern, as you probably know, contains a static method Instance which will create the instance if and only if it exists and return that instance. There is no reason that other or all methods of the singleton could not be static. However, given that there is ever only one instance of the class i'm not sure it makes sense to make everything else static. Does that make sense?

like image 26
Bejmax Avatar answered Sep 13 '25 00:09

Bejmax