Static class object

Why are static class objects allowed in C ++? what is their use?

#include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff in class*/ }; int main() { Test t; getchar(); return 0; } 
+4
source share
2 answers

It just works; the compiler should not do anything special simply because self is a static member of Test and is of type Test . I see no reason why this special case should be specifically prohibited.

Now there is a problem with Test::self in that you declare a variable but cannot define it. However, this is just a bug in the code and is easily fixed:

 class Test { ... }; Test Test::self; // <--- the definition int main() { ... 
+4
source

You use it for things that are shared between all instances of the class. For example, you can use it to implement a Singleton pattern .

+4
source

Source: https://habr.com/ru/post/1393492/


All Articles