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 useasDouble()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)explicitKeyword 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 newandplacement new :
    • new operatorProduce objects on the heap, allocate memory, and call constructors;
    • operator newAllocate only memory (not necessarily on the heap) without calling constructors;
    • placement newThe constructor is called on allocated memory.
  • delete operatorandoperator delete:
    • delete operatorDestruct and free memory;
    • operator deleteOnly memory is freed.
  • Array-orientednew operatoranddelete operator: On each object in the array as opposed to a single objectnewanddeleteOperation.