More Effective C++ book notes
Fundamental issues
Clause 1: Carefully distinguish Pointers from References
Pointers and references are similar in that they can be used for indirect reference operations on other objects, but there are differences between the two, and this difference is also an important basis for using Pointers or references. The details are as follows:
- The reference must be initialized and always refers to the object originally assigned, unalterable. This is more referential than Pointers, which can be assigned to null and can change direction, and are more flexible. Pointers are more flexible and more suitable unless the directivity in the program is constant (proper reference).
- The other way the book talks about implementing certain operators, specifically having to return someSomething that can be used as an assignment objectIn order to
[]
For example, a reference is used in this case.
Personally understand this kind of situation distinction degree is higher, if[]
If the return value is a pointer type, the following occursvector<int> num(10); // [] Returns a reference, currently implemented by STL num[0] = 1; // [] returns a pointer, which is misleading as a vector *num[0] = 1; Copy the code
It is best to use the C++ transition operator
(type) expression C++ provides four new conversion operators, using the xxx_cast
(expression) :
static_cast
And:C
The type converters of the format work basically the sameconst_cast
: Changes constants and variability, most commonly usedTo remove the constancy of an object. (that is, remove const)dynamic_cast
: Secure in the inheritance systemDownward transformation or cross-departmental transformationAction that converts a pointer or reference to a base class to a pointer or object to a derived class.reinterpret_cast
: used to convert function pointer types, strongly platform dependent,Try not to.
Never treat arrays polymorphically
Understanding: Array objects almost always involve pointer arithmetic, and polymorphic and pointer arithmetic cannot be used together.
Do not provide default constructor unless necessary
If default constructor is provided for the convenience of the class, some of the fields will be meaningless and the quality of the software will deteriorate.