What's the recommended practice regarding the using
declaration (e.g using std::vector;
)?
Should it be at the top of the cpp/cc file or just in the scope where it's being used?
What's the recommended practice regarding the using
declaration (e.g using std::vector;
)?
Should it be at the top of the cpp/cc file or just in the scope where it's being used?
Limiting its scope would be better in general, but it would take a non-trivial amount of code in your source file to make a difference in practice.
Chapter 59 of C++ Coding Standards by Sutter and Alexandrescu is named "Don't write namespace usings in a header file or before #include". So they say that you should not write using declaration or using directive before an #include directive, because this may influence the #included code. This also implies that you should not write using in your own header files, cause someone may #include them and this would alter the behavior in the inclusion point (see e.g. some Boost header library).
So don't write using in header files and before #include directive. Feel free to write using in your implementation files after #including directives.
If it is in a cpp file it is a matter of style. Some people have a preference to avoid using
declarations all together to avoid any ambiguity. If in a header, always have it in at least some scope, otherwise stick to the rule for variables: Always try to have things in the smallest scope as possible.
For readability its better to have it at the beginning. Otherwise, use it in the smallest scope possible.
To make the code clearer to other, you should avoid using using
.
update:
Please take mezhaka's comment into account. I wasn't precise enough, but referred with "at the beginning" to the beginning of the "real" code, i.e. after the #includes
's