More effective tive C ++ (1)

Source: Internet
Author: User
Tags try catch types of functions

Item M1: difference between pointer and reference

The reference must be initialized and cannot be changed to make it an alias for another variable.

Item M2: C ++ type conversion whenever possible

Such type conversion is easy to recognize for humans and programs. They allow the compiler to detect errors that cannot be found.
You can use dynamic_cast to convert a pointer or reference to a base class to a pointer or reference to its derived class or its sibling class, and you can know whether the conversion is successful. If the conversion fails, a null pointer is returned (when type conversion is performed on the pointer) or an exception is thrown (when type conversion is performed on the reference ). Dynamic_cast can only be converted between classes with inheritance relationships.
The most common purpose of reinterpret_cast is to convert between function pointer types.
Reinterpret_cast <type> (expression) the expression must be a pointer or reference !!!

Item m3: Do not use polymorphism for Arrays

Because the size of the derived class is generally not the same as that of the base class, and the storage method of the array is continuous in the memory. Therefore, base [I] and derive [I] Do not point to the same location.
In the language specification, a base class pointer is used to delete an array containing a derived class object, and the result is uncertain.
Polymorphism and pointer algorithms cannot be used together, so arrays and polymorphism cannot be used together.

Item M4: avoid useless Default constructors

Providing meaningless Default constructors also affects the efficiency of classes. Because the default constructor generally cannot ensure that all members are correctly initialized, data members must be judged in other member functions to ensure effective initialization. This will increase the number of executable programs.
However, if the default constructor is not used:
There is a problem when creating an object array.
They cannot be used in many template-based container classes. When instantiating a template, the template type parameter should provide a default constructor, which is a common requirement.

Item M5: exercise caution in defining type conversion functions

There are two types of functions that allow the compiler to perform these conversions: Single-argument constructors and implicit type conversion operators.
Class rational {
Public:
...
Operator double () const; // convert rational class to double type
};
Rational r (1, 2 );
Cout <R;
If the <operator is not overloaded, no error is prompted. Because R can be converted to floating point type using operator double.
The implicit conversion problem caused by Single-parameter constructors is even greater than that caused by implicit conversion operators.
The method without declaring operators can overcome the disadvantages of implicit type conversion operators. Implicit type conversion can be solved by adding the explicit keyword to the single-parameter constructor.

Item M6: differences between prefix and suffix of auto increment and Decrement Operators

The auto-increment and auto-increment suffixes return the const object. If it is not a const object, the I ++; statement is allowed. This is not allowed !!!

Item M7: Do not reload "&", "|", or ","

C ++ uses the Boolean expression short-circuit evaluate method. For example, if (P! = NULL & P ++) If P is null, P ++ will not calculate
If operator & overload & is used, the short-circuit evaluation method will be replaced by the function call method.
If (expression1 & expression2) is changed:
If (expression1.operator & (expression2) // when operaotr & is a member function
If (operator & (expression1, expression2) // when operaotr & is a global function
It calculates all its parameters, and the operation sequence is uncertain.
A comma-containing expression first calculates the expression on the left of the comma and then the expression on the right of the comma. The result of the entire expression is the value of the expression on the right of the comma.
There is no way to guarantee the order of calculation when the comma operator is overloaded.

Item M8: New and delete for different meanings

Differences between new operators and new operators
String * PS = new string ("Memory Management ");
You use the new operator. This operator is just like sizeof which is built in a language. You cannot change its meaning and its functions are always the same. The functions to be completed are divided into two parts. The first part is to allocate enough memory to accommodate the required types of objects. The second part is that it calls the constructor to initialize objects in the memory. The new operator always does these two things, and you cannot change its behavior in any way.
The delete operator is opposite to the new operator. It calls the Destructor first and then deletes the memory.
The new operator indicates that the name of the function called for memory allocation is Operator new. Therefore, you can modify the Memory Request behavior of the new operator by reloading the new operation (operator new.
Void * operator new (size_t size );
Usage:
Void * buffer = Operator new (50); // 50 indicates the size.
Operator Delete (buffer );

Placement new (a special operator new)
It is used to construct objects in (raw) memory that has been allocated but not yet processed.
Definition:
Void * operator new (size_t, void * location)
{
Return location;
}
Usage:
New (buffer) widget (widgetsize); // buffer is the memory space address that has been applied
Placement new is part of the standard C ++ library. To use placement new, you must use the statement # include <New>.
Operator new [] and operator Delete [] can also be overloaded to operate object arrays.

To call the corresponding new, use the corresponding Delete instead of mixing them.

Item M9: Use destructor to prevent resource leakage

You should say goodbye to pointers that manipulate local resources. Use smart pointers instead. (The pointer usage is concise, which is also applicable to exceptions)

Item M10: prevent resource leakage in Constructors

When an exception occurs during the execution of the constructor, the allocated memory space cannot be released. Because at this time, the Destructor will not be executed.
You can use exception handling to release the memory in the catch block after an exception is caught in the constructor.
The member pointer variable is replaced by the smart pointer auto_ptr. When the object disappears, it is automatically called.

Item M11: Prohibit exceptions from being passed out of the destructor

There are two reasons to prohibit the transfer of exceptions to the destructor. First, you can prevent terminate from being called during Stack-unwinding. Second, it can help ensure that the Destructor can always accomplish everything we want it to do. (If the exception is passed from the destructor to the outside, terminate will be automatically called to completely terminate your program)
Generally, try catch is used in the destructor to catch any exceptions generated by the destructor.
(Stack rollback: Stack rollback. If an exception occurs in a function and throw is executed to throw the exception object, the objects in the stack will be automatically parsed until catch is encountered .)

Item M12: understand the difference between "throwing an exception" and "passing a parameter" or "calling a virtual function"

Passing function parameters and exceptions can both be passing values, passing references, or passing pointers, which is the same. When you pass parameters and exceptions, the operation process to be completed by the system is completely different. The reason for this difference is: when you call a function, the control of the program will eventually return to the function call, but when you throw an exception, control will never return to the place where an exception is thrown.
When a parameter is referenced, the reference points to the actual object. When an exception is passed, the object will be copied, either by passing the value or by referencing it. (If an exception occurs, the original exception object will be removed from the living space, and its destructor will also be called .) The object will be copied even if it is static and will not be released.
Because exceptions always copy objects, the running speed of thrown exceptions is slightly slower.
When copying an object, the static type copy constructor is used instead of the dynamic type.
For example:
Class base {...};
Class derive: public base {...};
Derive D;
Base & B = D;
In throw B, only the Base copy structure is called.
Another difference is that a temporary object cannot be transferred to a non-const reference type parameter in a function call, but is allowed in an exception.
If exceptions are captured by pointers, the exception object must be global or heap! When pointer passing is abnormal, only the copy of the pointer is passed.
Implicit type conversion may occur during function calls. However, when an exception is caught, there is no type conversion. For example, catch (double D) does not capture the int type exceptions. (However, there may be conversions between the inheritance class and the base class. For example, you can capture exceptions of the base class to capture exceptions of the derived class type. Also, it can be converted from a typed pointer to an untyped pointer, so the catch clause with the const void * pointer can catch any type of pointer type exception)
The order in which catch clauses perform exception type matching is the order in which they appear in the source code. The first catch with successful type matching will be used for execution. When an object calls a virtual function, the selected function is located in the class that best matches the object type.

Item M13: capture exceptions through reference

Four standard exceptions:
Bad_alloc: thrown when operator new cannot allocate enough memory
Bad_cast: When dynamic_cast fails a reference operation
Bad_typeid: thrown when dynamic_cast operates on Null pointers
Bad_exception: used for unexpected exceptions
The exception is caught by Pointer. After the exception is handled, you cannot determine whether to delete the exception object. (If it is a global object, you do not need to delete it. If it is a heap object, you need to delete it .)
When they are thrown, the system copies the exception objects twice. In addition, there will be slicing problem, that is, when the exception object of the derived class is captured as the base class exception object, its derived class behavior will be cut off (sliced off ).
When an exception is captured by reference, no object deletion issues occur. There is no slicing problem (virtual functions can be called through the parent class reference to achieve polymorphism ). The exception object is copied only once. (So try to use "Reference to capture exceptions ")
(Reference is another method that can produce polymorphism effects except pointers .)

Item m14: exception specifications)

If a function throws an exception that is not within the exception specification range, the system can detect this error at runtime, and then a special function unexpected will be automatically called. Unexpected calls the terminate function by default.
Void F1 (); // no exception specification is declared and any exception can be thrown.
Void F2 () Throw (INT); // throw an int type exception
Void F2 () Throw (INT)
{
F1 (); // The exception thrown by F1 is not int, but valid
}
However, the exception thrown by the function is different from the exception type of the function that is called, and such a call may cause your program execution to be terminated.

Item M15: System overhead of Exception Handling

To handle exceptions at runtime, the program must record a large amount of information.

Item M16: Keep in mind the 80-20 criterion (80-20 rule)

About 20% of the Code uses 80% of program resources.
Try to use tools to find the system's bottle diameter, such as profiler, instead of human observation or intuitive judgment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.