Where to place the declaration of use

What is the best practice for using declarations (e.g. using std::vector; )?

Should it be at the top of the cpp / cc file or only in the area where it is used?

+4
source share
4 answers

For ease of reading, it is better to have it at the beginning. Otherwise, use it in the smallest possible area.

To make the code more understandable to another, you should avoid using using .

Update

Please consider the mjaka comment. I was not precise enough, but referred to "at the beginning" at the beginning of the "real" code, i.e. After #includes

0
source

Limiting its size would be better overall, but your source file would require a non-trivial amount of code to make a difference in practice.

+2
source

Chapter 59 of the C ++ standards for encoding Sutter and Alexandrescu is entitled "Do not write namespace names in the header file or before #include". Therefore, they say that you should not write using the declaration or using the directive before the #include directive, because this may affect #included. It also means that you should not write in your own header files, because someone can # include them, and this will change the behavior at the inclusion point (see, for example, some Boost header library).

Therefore, do not write using the header files and before the #include directive. Feel free to write in the implementation files after the #include directives.

+2
source

If it is in the cpp file, this is a style issue. Some people prefer to avoid using declarations to avoid any ambiguity. If the header always has it, at least in some area, otherwise you follow the rule for variables: always try to have things in the smallest area as possible.

0
source

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


All Articles