What's the scope of the “using” declaration in C++?

后端 未结 7 632
醉话见心
醉话见心 2020-12-07 19:45

I\'m using the \'using\' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary \'std::\'s).

using std::str         


        
相关标签:
7条回答
  • 2020-12-07 20:03

    The scope of the using statement depends on where it is located in the code:

    • Placed at the top of a file, it has scope throughout that file.
    • If this is a header file, it will have scope in all files that include that header. In general, this is "not a good idea" as it can have unexpected side effects
    • Otherwise the using statement has scope within the block that contains it from the point it occurs to the end of the block. If it is placed within a method, it will have scope within that method. If it is placed within a class definition it will have scope within that class.
    0 讨论(0)
  • 2020-12-07 20:13

    There are a few comments that are rather unqualified when they say "Don't". That is too stern, but you have to understand when it is OK.

    Writing using std::string is never OK. Writing using ImplementationDetail::Foo in your own header, when that header declares ImplementationDetail::Foo can be OK, moreso if the using declaration happens in your namespace. E.g.

    namespace MyNS {
        namespace ImplementationDetail {
            int Foo;
        }
        using ImplementationDetail::Foo;
    }
    
    0 讨论(0)
  • 2020-12-07 20:16

    When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a using declaration has the exact same effect of placing the using declaration at the top of each file that includes that header file.

    0 讨论(0)
  • 2020-12-07 20:25

    There's nothing special about header files that would keep the using declaration out. It's a simple text substitution before the compilation even starts.

    You can limit a using declaration to a scope:

    void myFunction()
    {
       using namespace std; // only applies to the function's scope
       vector<int> myVector;
    }
    
    0 讨论(0)
  • 2020-12-07 20:27

    That is correct. The scope is the module that uses the using declaration. If any header files that a module includes have using declarations, the scope of those declarations will be that module, as well as any other modules that include the same headers.

    0 讨论(0)
  • 2020-12-07 20:28

    The scope is whatever scope the using declaration is in.

    If this is global scope, then it will be at global scope. If it is in global scope of a header file, then it will be in the global scope of every source file that includes the header.

    So, the general advice is to avoid using declarations in global scope of header files.

    0 讨论(0)
提交回复
热议问题