Static member versus static global

I read that the difference between global and static global values ​​is that the global variable can be referenced in another implementation file via extern, while static global locales are localized only for this implementation file. For more information, see These two questions: [ 1 , 2 ].

From what I understand, this means that the following foo() and bar() should be connected the same way. Both functions can only be used by MyClass .

 //MyClass.h Class MyClass{ private: static void foo(); }; //MyClass.cpp void MyClass::foo(){} static void bar(){} 

I see that the declaration of foo() more common, as it allows the header file to fully lay out the entire class (even if you cannot / should not use personal things), but this is bad practice declaring a function like bar() (hidden from the header file )?

In the context, I define WNDPROC for Windows messages that should be static, but this is a pretty ugly declaration, and I'm not sure if I should completely hide it in the implementation file or continue declare it in the header file.

+4
source share
1 answer

static is a very terrible keyword because it has many different meanings depending on the context. static variables and static functions are completely different, and the static function in the class and the static free function are completely different.

A static function in a class means that a function can be called without an instance of the class, but it cannot access non-stationary members of the class. This is a bit like a regular function just nested in a class for convenience.

A static free function has an internal binding, so it cannot be seen outside the source file, and its name can be reused in other source files.

The static function of a class has no internal relationship. All class functions have an external connection. You can split the class function between the header and the source files, regardless of whether the class function is static or not.

I recommend that you read some tutorials / books to more clearly understand the many different uses of statics. When you see statics in a place that you have not seen before, do not take anything!

If you have a free function that you want to hide in the source file, you can declare it static, as you did. Alternatively, you can put it in an unnamed namespace.

 // cpp file only namespace { void hiddenfunc() {..} } 

It looks like

 static void hiddenfunc(); 

And it can be called in the same way (as "hiddenfunc ()"). The advantage of unnamed namespaces (this is a strange name, I know) is that you can also place classes and other definitions that you want to see only in this source file. Just make sure that you define the function body in the namespace area {..}. Do not put the unnamed namespace in the header file.

+8
source

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


All Articles