Why should we only use "static" inside a class or function (C ++)?

I recently read Stroustrups C ++ programming language and in the section on Linkage in chapter 9 I came across the following paragraph:

"In C and older C ++ programs, the static keyword is (vaguely) used to mean" use internal communication. "Do not use static except internal functions and classes."

The problem is that, reading further, the author did not specify why this is bad practice. I use static functions from time to time in my code, usually for some simple calculations that are not needed outside the compilation module, but I never realized that this was underestimated, and for me it is not obvious why this is bad. Can someone shed some light on this for me please?

+6
source share
2 answers

I think the idea is not to frown on the internal connection, but to avoid confusion with the new static value: static has too many values ​​(declaring material with internal connection, defining local variables with static storage, duration, marking non-instance classes) , so avoiding one of the less intuitive is good.

Because of this, the C ++ 98 standard provides another way to declare material with internal binding: unnamed namespaces and invalidates static "when declaring objects in the namespace scope".

The C ++ 11 standard removed this fatigue (and also somehow changed the semantics of unnamed namespaces without requiring internal binding), so now it's really a matter of style.

+5
source

Because in C ++, anonymous namespaces should be preferred, which basically offer the same functionality.

I think that static in this context is not approved because of double values ​​and the fact that the two values ​​are completely opposite - if inside a class or struct it represents a global state, while outside it gives an internal binding and provides a copy of the variable or method for each translation unit.

Moreso, static can only be applied to functions and variables, while inside an anonymous namespace you can have type declarations.

 namespace //OK { class X {}; } static class X //syntactically correct, but does nothing { }; 

Note that the standard considers using static to specify bindings as deprecated.

+4
source

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


All Articles