File: namespaces.yo

package info (click to toggle)
c%2B%2B-annotations 10.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,536 kB
  • ctags: 3,247
  • sloc: cpp: 19,157; makefile: 1,521; ansic: 165; sh: 128; perl: 90
file content (60 lines) | stat: -rw-r--r-- 2,388 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
When entities from hi(namespace) namespaces are used in hi(header file) header
files, no ti(using) directive should be specified in those header
files if they are to be used as general header files declaring classes or
other entities from a i(library). When the tt(using) directive is used in a
header file then users of such a header file are forced to accept and use the
declarations in all code that includes the particular header file.

    For example, if in a namespace tt(special) an object tt(Inserter cout) is
declared, then tt(special::cout) is of course a different object than
tt(std::cout). Now, if a class tt(Flaw) is constructed, in which the
constructor expects a reference to a tt(special::Inserter), then the class
should be constructed as follows:
        verb(
    class special::Inserter;

    class Flaw
    {
        public:
            Flaw(special::Inserter &ins);
    };
        )
    Now the person designing the class tt(Flaw) may be in a lazy mood, and
might get bored by continuously having to prefix tt(special::) before every
entity from that namespace. So, the following construction is used:
        verb(
    using namespace special;

    class Inserter;
    class Flaw
    {
        public:
            Flaw(Inserter &ins);
    };
        )
    This works fine, up to the point where somebody wants to include
tt(flaw.h) in other source files: because of the tt(using) directive, this
latter person is now by implication also tt(using namespace special), which
could produce unwanted or unexpected effects:
        verb(
    #include <flaw.h>
    #include <iostream>

    using std::cout;

    int main()
    {
        cout << "starting\n";       // won't compile
    }
        )
    The compiler is confronted with two interpretations for tt(cout): first,
because of the tt(using) directive in the tt(flaw.h) header file, it considers
tt(cout) a tt(special::Inserter), then, because of the tt(using) directive in
the user program, it considers tt(cout) a tt(std::ostream). Consequently,
the compiler reports an error.

    As a i(rule of thumb), header files intended for general use
should not contain tt(using) declarations. This rule does not hold true for
header files which are only included by the sources of a class: here the
programmer is free to apply as many tt(using) declarations as desired, as
these directives never reach other sources.