Second, scope
1. Namespaces (namespaces)
In the. cc file, the use of unnamed namespaces is advocated (unnamed namespaces, translator Note: Unnamed namespaces are like unnamed classes, which seem to be introduced rarely:-(). when using a named namespace, its name can be based on the project or path name, not using a using indicator .
Definition: Namespaces divide the global scope into distinct, named scopes, effectively preventing naming conflicts for global scopes.
Pros: Namespaces provide (can be nested) named axes (name axis, translator note: Split names in different namespaces), and of course, classes also provide (nested) named axes (the translator notes: Split the names within the scope of different classes).
Conclusion: Use namespaces appropriately according to the strategies that are mentioned below.
1) Unnamed namespace (Unnamed namespaces)
In the. cc file, it is permissible to even advocate the use of unnamed namespaces to avoid runtime naming conflicts:
namespace {///. cc File//namespace contents do not need to indent enum {UNUSED, EOF, ERROR};<span style= "White-space:pre" ></span>//frequently used characters number bool Ateof () {return pos_ = = EOF; Use the symbols in this namespace EOF} //namespace
However, file scope declarations associated with a particular class are declared in the class as a type, a static data member, or a static member function, rather than a member of an unnamed namespace. As shown above, the unnamed namespace is identified with a comment//namespace at the end.
You cannot use an unnamed namespace in an. h file.
2) named namespace (Named namespaces)
The named namespaces are used in the following ways:
namespace will In addition to the file inclusion, the declaration/definition of the global identity, and the predecessor declaration of the class the entire source file is encapsulated to distinguish it from other namespaces.
. h file namespace MyNamespace {//All declarations are placed in the namespace//take care not to use indentation class MyClass {public:...void Foo ();};} namespace mynamespace//. cc Files namespace MyNamespace {///function definitions are placed in the namespace void Myclass::foo () {...}} Namespace MyNamespace
The usual. cc files contain more, more complex details, including references to classes in other namespaces, and so on.
#include "a.h" Define_bool (Someflag, False, "dummy flag"); Class C; The predecessor Declaration of class C in the global namespace namespace a {Class A;} Pre-declaration of class a::a in namespace a namespace B {... code for b...//B} //namespace B
do not declare anything under the namespace STD, including the pre-declaration of the standard Library class. Declaring an entity under STD can result in ambiguous behavior, such as non-portability.
declares the entity under the standard library and needs to include the corresponding header file.
It is best not to use the using indicator to ensure that all names under the namespace are working properly.
Prohibition-polluting namespaces using namespace Foo;
In a function, method, or class of a. cc file,. h file, you can use the using.
Allow:. cc files in//. h files must be used within a function, method, or class using using:: Foo::bar;
You can also use namespace aliases in functions, methods, or classes of. cc files,. h files.
Allow:. cc files in//. h files must be used inside a function, method, or class namespace FBZ =:: Foo::bar::baz;
2. Nested classes (Nested Class)
While exposing nested classes as part of an interface, although you can keep them in the global scope directly, it is a better choice to place the declaration of a nested class in a namespace.
Definition: Another class can be defined in one class, and a nested class is also called a member class (member Class).
class Foo {private://bar is a member class that is nested in Foo. {...};};
Pros: When nested (member) classes are only useful when used in nested classes (enclosing class), placing them in nested class scopes as members of nested classes does not pollute other scopes with the same name class. You can nest a nested class in a nested class, define a nested class in a. cc file, and avoid including the definition of a nested class in a nested class, because the definition of a nested class is usually related only to the implementation.
Disadvantage: You can only pre-declare nested classes in the definition of a nested class. Therefore, any header file that uses the foo::bar* pointer must contain the declaration of the entire Foo.
Conclusion: Do not define nested classes as public unless they are part of an interface, for example, a method uses a series of options for this class.
3. Non-member functions (nonmember), static member functions (Statics Member), and global Functions
Use a non-member function or a static member function in a namespace, and try not to use a global function.
Pros: In some cases, non-member functions and static member functions are useful, and non-member functions can be placed in namespaces to avoid contamination of global scopes.
Disadvantage: It may be more meaningful to have non-member functions and static member functions as members of new classes, especially if they require access to external resources or have important dependencies.
Conclusion:
Sometimes it is useful not to qualify a function in a class's entity, or even to do so, either as a static member or as a non-member function. Non-member functions should not be dependent on external variables and should be placed in a namespace as much as possible. Instead of creating a class simply to encapsulate several static member functions that do not share any static data, use a namespace.
functions defined in the same compilation unit, which are called directly by other compilation units, may introduce unnecessary coupling and connection dependencies, which are particularly sensitive to static member functions. You can consider extracting into a new class, or placing a function in a separate library's namespace.
If you do need to define a non-member function and just use it in a. cc file, you can use an unnamed namespace or a static association (such as static int Foo () {...} ) to qualify its scope.
4. Locals (local Variables)
Place a function variable in the smallest scope possible, initializing it when declaring a variable.
C + + allows variables to be declared anywhere in the function. We advocate declaring variables in the smallest possible scope, as well as getting closer to the first use. This makes the code easy to read and easily locates the declaration position, variable type, and initial value of the variable. In particular, you should use initialization instead of declaring + assigning.
int i;
i = f (); Bad--initialization and declaration separation
NT J = g (); Good--declaration at initialization
Note: GCC correctly executes for (int i = 0; i < ++i) (the scope of I is limited to for loops only), so I can be reused in other for loops. The scope Declaration (Scope declaration) is also correct in statements such as if and while.
while (const char* p = STRCHR (str, '/')) str = p + 1;
Note: If the variable is an object, each entry to the scope calls its constructor, and each exit scope calls its destructor.
Low-efficiency implementations
for (int i = 0; i < 1000000; ++i) {
Foo F; Constructors and destructors are called 1 million times, respectively!
F.dosomething (i);
}
It is much more efficient to declare a similar variable to be declared outside the circular action:
Foo F; Constructors and destructors call only 1 times
for (int i = 0; i < 1000000; ++i) {f.dosomething (i);
}
5. Global variables (Globals Variables)
Global variables of class type are forbidden, and global variables of the built-in type are allowed, of course, the very number of global variables in multithreaded code is also forbidden. Never initialize a global variable with a function return value.
Unfortunately, the constructors for global variables, destructors, and invocation order of initialization operations are only partially specified, and each generation is likely to change, resulting in hard-to-find bugs.
Therefore, it is forbidden to use global variables of class type (including STL strings, vectors, and so on), because their initialization order may cause problems with the construction. Built-in types and structs with no constructors constructed from built-in types
Can be used, if you must use a global variable of class type, use single-piece mode (singleton pattern).
For global string constants, use C-style strings instead of STL strings:
const char kfrogsays[] = "Ribbet";
Although it is permissible to use global variables in global scope, it is important to think twice. Most global variables should be static data members of a class or, when used only in. cc files, be defined in an unnamed namespace, or use a static association to limit the scope of a variable.
Remember, static member variables are considered global variables, so they cannot be class types!
Translator: This article mainly refers to the scope of some rules, summed up:
1. The unnamed namespace in cc avoids naming conflicts, scoping, and avoids polluting namespaces directly using the using prompt;
2. Nested classes conform to the local use principle, but can not be in the other header file in front of the declaration, try not to public;
3. As far as possible without global functions and global variables, consider scope and namespace constraints, as far as possible to form a single compilation unit;
4. Global variables in multiple threads (with static member variables) do not use class types (including STL containers) to avoid bugs caused by ambiguous behavior.
The use of scopes, in addition to name pollution, readability, mainly to reduce the coupling, improve the efficiency of compilation and execution.
For example, the global scope of two different projects has a class Foo, which can cause conflicts when compiling or running. If each project puts code in a different namespace, Project1::foo and Project2::foo will naturally not conflict as distinct symbols.
Cons: namespaces are confusing because they provide an additional (nested) named Axis as a class. Using an unnamed space in a header file can easily violate the unique definition principle of C + + (one definition rule (ODR)).
Google C + + Style Guide----scope