C++ using keyword

后端 未结 4 1259
醉话见心
醉话见心 2021-02-12 22:27

What is the difference between these two usage of using keyword:

using boost::shared_ptr;

and

using namespace boo         


        
相关标签:
4条回答
  • 2021-02-12 23:07

    The first is called using declaration;

    The second is called using directive.

    Quoting MSDN:

    Note the difference between the using directive and the using declaration:

    the using declaration allows an individual name to be used without qualification,

    the using directive allows all the names in a namespace to be used without qualification.

    0 讨论(0)
  • 2021-02-12 23:30

    The first only allows you to use the name shared_ptr without the boost:: prefix. The second allows you to use any and all names in the boost namespace withoout the boost:: prefix. Some people frown on the latter but it's never given me any problems.

    0 讨论(0)
  • 2021-02-12 23:34
    using boost::shared_ptr;
    

    Includes only the shared_ptr from the boost namespace in your current namespace. This means you can use the shared_ptr without qualifying it with namespace boost.

    It is called a using declaration.


    using namespace boost;
    

    Includes all the symbols in the boost namespace in your current scope. This means you can use all the symbols in the boostnamespace without qualifying them with namespace boost.

    It is called as using directive.


    Why should you always prefer using declaration over using directive?

    It is always better to use the first(using declaration) and avoid the second(using directive) because the second causes namespace pollution by bringing in potentially huge numbers of names in to the current namespace, many of which are unnecessary. The presence of the unnecessary names greatly increases the possibility of unintended name conflicts.

    To quote Herb Sutter on the usage of using directive:

    I find it helpful to think of a using directive as a marauding army of crazed barbarians that sows indiscriminate destruction wherever it passes--something that by its mere presence can cause unintended conflicts, even when you think you're allied with it.

    0 讨论(0)
  • 2021-02-12 23:34
    • using namespace boost makes all names in the boost namespace visible without qualification
    • using boost::shared_ptr just makes shared_ptr visible without qualification.
    0 讨论(0)
提交回复
热议问题