Terminology)
By Scott Meyers
Translator: fatalerror99 (itepub's nirvana)
Release: http://blog.csdn.net/fatalerror99/
This is a small C ++ Vocabulary (Vocabulary) that all programmers should understand ). The following terms are important enough. It is absolutely necessary for us to completely agree on their meaning.
Declaration(Declaration) tells the compiler about the name and type of something, but it ignores some details. The following are all declarations ):
Extern int X; // object Declaration
STD: size_t numdigits (INT number); // function declaration
Class widget; // class declaration
Template <typename T> // template declaration
Class graphnode; // (see item 42 for info on
// The use of "typename ")
Note that even if it is built-in type (built-in type), I prefer to regard integer x as an "object ", some people keep the "object" name to user-defined type (user-defined type), but I am not one of them. The return type of the numdigits function is STD: size_t, that is, size_t type in the namespace (namespace) STD. This namespace is where everything in the C ++ standard library is actually located. However, because the c Standard Library (strictly speaking, from c89) can also be used in C ++, symbols inherited from C (such as size_t) may exist in the global scope, either inside STD or both. This depends on which header file is # include. In this book, I assume that the C ++ header file is # include, which is why I replaced size_t with STD: size_t. When the standard library components are involved in the text discussion, I generally do not mention STD, which relies on your approval that everything like size_t, vector, and cout is in STD, in the sample code, I always include STD, because the real Code cannot be compiled without it.
By the way, size_t is only a type of unsigned typedef for C ++ to count something (for example, a char *-Based String (char *-Based String) the number of characters, the number of elements in an STL container (container), and so on ). It is also the type held by the operator [] function of vector, deque, and string. This is a convention to be followed when we define our own operator [] function in item 3.
The Declaration (Declaration) of each function indicates itsSignature(Feature identification), that is, its parameters and return types. The signature of a function is of the same type as that of a function. For numdigits, signature is STD: size_t (INT), that is, "the function gets an int and returns a STD: size_t ". The C ++ definition of the official "signature" (Feature Recognition) excludes the return type of the function, but in this book, the return type is considered as signature (Feature Recognition) is more useful.
Definition(Definition) provides the compiler with the details omitted during Declaration (Declaration. For an object, definition is the place where the compiler sets aside memory for the object. For a function or a function template, definition provides a code ontology. For a class or a class template, definition lists the members (members) of the class or template ):
Int X; // object definition
STD: size_t numdigits (INT number) // function definition.
{// (This function returns
STD: size_t digitssofar = 1; // The number of digits
// In its parameter .)
While (number/= 10 )! = 0) ++ digitssofar;
Return digitssofar;
}
Class widget {// class definition
Public:
Widget ();
~ Widget ();
...
};
Template <typename T> // template Definition
Class graphnode {
Public:
Graphnode ();
~ Graphnode ();
...
};
Initialization(Initialization) is the process of setting the first value of an object. For objects (objects) generated by structs or classes, initialization (initialization) is completed through Constructors (constructors.Default constructor(Default constructor) is the one that can be called without any arguments (real parameters. Such a constructor (constructor) can have neither parameters nor every parameter (parameter) has a default value (the original paragraph is incorrect, changes based on the author's website Errata-Translator's note .) :
Class {
Public:
A (); // default constructor
};
Class B {
Public:
Explicit B (INT x = 0, bool B = true); // default constructor; see below
}; // For info on "Explicit"
Class C {
Public:
Explicit C (int x); // not a default constructor
};
Here, both the constructors of classes B and C are declared as explicit ). This is to prevent them from being used to execute implicit type conversions (implicit type conversion), although they can also be used for explicit type conversions (display type conversion ):
Void dosomething (B bobject); // a function taking an object
// Type B
B bobj1; // an object of type B
Dosomething (bobj1); // fine, passes a B to dosomething
B bobj2 (28); // fine, creates a B from the int 28
// (The bool defaults to true)
Dosomething (28); // error! Dosomething takes a B,
// Not an int, and there is no
// Implicit conversion from int to B
Dosomething (B (28)); // Fine, uses the B constructor
// Explicitly convert (I. e., cast)
// Int to a B for this call. (See
// Item 27 for info on casting .)
Constructors declared as explicit are generally more desirable than non-explicit because they can prevent unexpected (often unintentional) Execution of compilers) type conversions ). Unless I have a good reason to allow a constructor (constructor) to be used for implicit type conversions (implicit type conversion), I declare it as explicit ). I hope you can follow the same rule.
Note how I highlight cast (force conversion) in the above sample code. Throughout this book, I use this to highlight the materials you should pay attention. (I also highlight the chapter number, but it is only because I want it to look better .)
Copy constructor(Copy constructor) is used to initialize another object of the same type with an object ),Copy assignment operator(Copy assignment operator) is used to copy the values of an object to another object of the same type:
Class widget {
Public:
Widget (); // default constructor
Widget (const widget & RHs); // copy constructor
Widget & operator = (const widget & RHs); // copy assignment operator
...
};
Widget W1; // invoke default constructor
Widget W2 (W1); // invoke copy constructor
W1 = W2; // invoke copy
// Assignment operator
When you see something that looks like an assignment (assign value), read it carefully, because "=" can also be used to call copy constructor (copy constructor) in syntax ):
Widget W3 = W2; // invoke copy constructor!
Fortunately, copy constructor (copy constructor) is easily distinguished from copy assignment (copy assignment. If a new object is defined (like W3 in the above line of code), a constructor (constructor) must be called; it cannot be an assignment (Value assignment ). If no new object is defined (like in the above line "W1 = W2" code), no Constructor (constructor) can be called, therefore, it is an assignment (Value assignment ).
Copy constructor is a very important function, because it defines how an object (object) is passed by value (passed by value ). For example, consider this:
Bool hasacceptablequality (widget W );
...
Widget awidget;
If (Hasacceptablequality (awidget))...
The parameter W is passed to hasacceptablequality by passing the value. Therefore, in the preceding call, awidget is copied to W. The copy action is executed by the copy constructor of the widget. Pass-by-value means "Call the copy constructor" (call the copy constructor ). (However, pass user-defined types by value (passing user-defined types by passing values) is usually a bad idea, pass-by-reference-to-const is usually a better choice. For details, see item 20 .)
STLIs a standard template library. As part of the C ++ standard library, it is dedicated to containers (containers) (such as vector, list, set, map, and so on ), iterators (iterator) (for example, vector <int>: iterator, set <string>: iterator, etc.), algorithms (algorithm) (for example, for_each, find, sort, and other functions. Many of the related functions have passedFunction objects(Function object) -- behavior is similar to the objects (object) of a function -- provided. Such objects (object) comes from the class (class) That reloads operator () -- function call operator --. If you are not familiar with STL, when reading this book, you should have a decent reference manual for future reference, because STL is so useful for me that I can't help but use it. Once you use it a little bit, you will feel the same way.
Programmers who come to C ++ from a language like Java or C # MayUndefined behaviorThe concept of (undefined behavior) is surprising. For various reasons, some constructs (structural components) in C ++ do not have a definite definition: you cannot reliably predict what will happen during the runtime. Here are two examples of code with undefined behavior (undefined behavior:
Int * p = 0; // P is a null pointer
STD: cout <* P;// Dereferencing a null poiNter
// Yields undefined behavior
Char name [] = "Darla"; // name is an array of Size 6 (don't
// Forget the trailing null !)
Char c = Name[10];// Referring to an invalid array index
// Yields undefined behavior
To emphasize that undefined behavior (undefined behavior) results are unpredictable and may be annoying, experienced C ++ programmers often say they have undefined behavior (undefined behavior) the program can (CAN) destroy the fruits of your hard work. This is true: a program with undefined behavior (undefined behavior)Cocould(Yes) destroy your painstaking efforts. However, the possibility is not very high. What's more likely is that the program is capricious, sometimes running normally, sometimes completely finished, and sometimes produces incorrect results. Powerful C ++ programmers can avoid undefined behavior (undefined behavior) at their best ). In this book, I will point out many things you must pay attention.
Another term that may confuse programmers who transfer data from other languages to C ++ is:Interface(Interface ). Both Java and. net use interfaces (Interface) as a language element, but this is not the case in C ++, but in item 31 we discuss how to simulate it. When I use the term "interface" (Interface), I usually talk about the signature of a function (feature recognition), a class (class) (for example, a class (class)'s "public interface", "protected interface", or "private interface"), or a template) must be a valid expressions (expression) (see item 41 ). That is to say, I talk about interfaces as a fairly general design concept.
Client(Customer) is someone or something that uses the code you write (generally interfaces (Interface. For example, the clients (customer) of a function is its user: the code snippet that calls this function (or holds its address) and the person who writes and maintains such code. The clients (customer) of a class or template is a component of the software that uses this class or template, and the programmer who writes and maintains the code. When discussing clients, I usually point to programmers because programmers are troubled and misled, or they are troubled by poor interfaces (interfaces. But they do not write code.
You may not be used to thinking about clients, but I will spend a lot of time trying to convince you that you should do your best to make their life easier. Remember, you are also a client (customer) of software developed by others ). Don't you want those people to make things easier for you? In addition, you will almost certainly find yourself in the position of your own client (customer) at some point (that is, using the code you write). At this time, you will be happy to maintain your concern for the client (customer) in your mind when developing your interfaces (interface.
In this book, I often cover up the differences between functions and function templates and between classes and class templates. That is because it is often possible to determine one of the items. Otherwise, I will treat classes (classes), functions (functions), and templates (templates) generated by classes (classes) and functions (functions) differently ).
When constructor and Destructors are mentioned in code comments, I sometimes use abbreviationsCtorAndDtor.
Naming Conventions (Naming Convention)
I tried to select meaningful names for objects (object), classes (class), functions (function), templates (Template), etc, however, the meaning behind some of my names may not appear immediately. For example, the two parameter names (parameter names) that I particularly like are LHS and RHS. They represent "left-hand side" and "right-hand side" respectively ". I often use them as the parameter names (parameter names) of functions that implement binary operators (Binary operators) (for example, operator = and operator ). For example, if a and B represent rational numbers of objects (objects), and if rational objects (objects) can use a non-member (non-member) operator * function multiplication (this is probably the case explained in item 24), expression
A * B
And function call
Operator * (A, B)
Is equivalent.
In item 24, I declare operator * as follows *:
Const rational operator * (const rational &LHS, Const rational &RHS);
As you can see, left-hand operand (left-hand operand) A appears as the LHS inside the function, while right-hand operand (right-hand operand) B appears as the RHS.
For member functions (member function), left-hand argument (left-hand parameter) is represented as this pointer (this pointer), so sometimes I use parameter name (parameter name) RHS separately. You may already declarations (Declaration) of some widgets in the member functions (member function) section on page 1 (this article introduces the example in the section of copy constructor (copy constructor)-Translator's note). This reminds me. I often use the widget class (class) in the example ). "Widget" does not mean anything. It only uses the name from time to time when I need the name of an example class. It has nothing to do with widgets in the GUI toolkit.
I often follow this rule to name pointers (pointer): A pointer (pointer) of an object (object) pointing to type (type) T is called PT, "pointer to t ". The following is an example:
Widget * PW; // PW = PTR to widget
Class airplane;
Airplane * pA; // Pa = PTR to airplane
Class gamecharacter;
Gamecharacter * PGC; // PGC = PTR to gamecharacter
I use a similar convention for references: RW can be considered as a reference to
Widget (to reference a widget), and Ra is a reference to an airplane (to reference an airplane ).
When discussing member functions (member functions), I occasionally use the name MF.
Threading considerations (thread considerations)
As a language, C ++ does not have the concept of threads (thread)-in fact, there is no concept of concurrency (concurrency. This is also true for the c ++ standard library. As far as the scope of C ++ is concerned, multithreaded programs (multi-threaded programming) does not exist.
And so far they still do. I am committed to making this book based on standard and portable C ++, but I cannot turn a blind eye to the fact that thread safety has become a problem for many programmers. My approach to dealing with the cracks between the standard C ++ and the reality is to point out that a certain C ++ constructs (structural component), with my analysis, is likely to be in the threaded environment (thread environment). This will not make this book a multithreaded programming with C ++ (using C ++ for multi-threaded programming) book. On the contrary, it will make this book quite a C ++ programming book: it will largely limit itself to the single-threaded (single-thread) idea, acknowledge the existence of multithreading (multithreading) and try to point out that thread-aware programmers need to pay special attention to evaluating the suggestions I provide.
If you are not familiar with multithreading (multithreading) or do not have to worry about it, you can ignore my thread discussion. If you are writing a multi-threaded application or library, remember my comments and use it as the starting point for the problem you need to solve when using C ++.
Tr1 and boost
You will find that tr1 and boost are everywhere in the book. Each of them has a special item to describe in some details (item 54 is tr1, item 55 is boost), but unfortunately these items are at the end of the book. (They are there because they are better. I did try many other places .) If you want to, you can open and read those items now, but if you prefer to start from the beginning rather than the end of the book, the following summary will help you:
- Tr1 ("Technical Report 1") is a specification (specification) for new functions added to the C ++ standard library ). These functions provide functions such as hash tables (hash table), reference-counting smart pointers (reference counting smart pointer) in the form of new class (class) and function templates (function template ), regular Expressions (Regular Expression), and so on. All tr1 components are nested in namespace tr1 within namespace STD.
- Boost is a portable, peer-reviewed, open-source C ++ library provided by an organization and a website (http://boost.org. Most tr1 functions work based on boost, and until the compiler vendor includes tr1 in their C ++ library release, the boost website is likely to remain the first stop for developers looking for tr1 implementation. Boost provides more things than tr1. In many cases, it is worth learning about.