More Effective C++ reading notes
The operator
Clause 5: Be wary of custom “type conversion functions.
Understanding: First, the type conversion function was called when it was not intended. The result may be incorrect, unintuitive, and difficult to debug. There are two types of such conversions: (1) implicit conversion operators and (2) constructor:
- The following is an example of an implicit conversion operator:
operator double(a) const; Copy the code
When this type conversion function is defined in a class, the class will be called by the compiler while in use, causing an error. The solution is to use
asDouble()
This function replaces the operator double function. - Constructor: a constructor that takes only one argument or many arguments but has default values for all arguments except for the first argument. There are two ways to deal with (1)
explicit
Keyword declares a single argument constructor so that the function cannot be implicitly cast; (2) UseThe proxy classTo construct the argument constructor.
Clause 6: Distinguish between the prefix and postfix forms of the Increment/Decrement operator
Understand: the difference between I ++ and ++ I, give the implementation code to see the difference
// Return a reference
UPInt& UPInt::operator+ + () {*this+ =1;
return *this;
}
// Return a const object
const UPInt UPint::operator+ + (int)
{
UPInt oldValue = *this; + + (*this); // Here we call the leading ++ operator
return oldValue;
}
Copy the code
Clause 7: don’t overload, &&, | |, and operators
To understand:
&&
and||
There areSudden death semantics, will be reloadedFunction call semanticsReplace, cause unanticipated effect. Among themSudden death semanticsIt means that once the true or false value of the expression is determined, even if some parts of the expression are not verified, the entire evaluation work is still directly finished. whileFunction call semanticsAll of the following expressions are executed.- If the expression contains
.
, the left side of the comma is evaluated first, then the right side of the comma, and the result of the final expression is represented by the return value on the right side, which is not possible when overloading the comma.
Understand the different meanings of new and delete
To understand:
new operator
.operator new
andplacement new
:new operator
Produce objects on the heap, allocate memory, and call constructors;operator new
Allocate only memory (not necessarily on the heap) without calling constructors;placement new
The constructor is called on allocated memory.
delete operator
andoperator delete
:delete operator
Destruct and free memory;operator delete
Only memory is freed.
- Array-oriented
new operator
anddelete operator
: On each object in the array as opposed to a single objectnew
anddelete
Operation.