Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using keyword

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

using boost::shared_ptr;

and

using namespace boost;
like image 283
Bitmap Avatar asked Aug 07 '11 13:08

Bitmap


People also ask

What is keyword in C with example?

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example: int money; Here, int is a keyword that indicates money is a variable of type int (integer).

Why keywords are used in C?

Keywords are predefined, reserved words in C language and each of which is associated with specific features. These words help us to use the functionality of C language. They have special meaning to the compilers. There are total 32 keywords in C.

What is the use of using keywords?

The using keyword has two major uses: The using statement defines a scope at the end of which an object will be disposed. The using directive creates an alias for a namespace or imports types defined in other namespaces.


2 Answers

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.

like image 122
Alok Save Avatar answered Sep 27 '22 19:09

Alok Save


  • using namespace boost makes all names in the boost namespace visible without qualification
  • using boost::shared_ptr just makes shared_ptr visible without qualification.
like image 43
David Heffernan Avatar answered Sep 27 '22 19:09

David Heffernan