Executive tive c ++ clause 26-31 "Implementation of class and function" arrangement, effective26-31

Source: Internet
Author: User

Executive tive c ++ clause 26-31 "Implementation of class and function" arrangement, effective26-31

I. Problems faced by class implementation:

Defining variables too quickly may lead to delays in efficiency; over-using the transformation (casts) may lead to slow code, difficult maintenance, and subtle and difficult-to-solve errors; the returned object "handls of internal data" may damage the encapsulation and leave it to the customer. The impact of exceptions may lead to resource leakage and data corruption; over-enthusiastic inlining may cause code expansion; over-coupling may lead to unsatisfactory lengthy build Times.

II. Article 26: try to delay the appearance of the variable definition

Some objects may be defined too early, but they are often imported during code execution. As a result, the defined objects are not used, the constructor has made a cost to analyze the composition.
So we should try to extend the definition as much as possible when defining the object, or even until the moment before the variable is used, until the initial value can be provided.
The advantage of doing so is that it not only avoids unnecessary (destructor) objects, but also avoids meaningless default constructor behavior.
What should I do in a loop? At this time, we usually have two options:
Method A: 1 constructor + 1 destructor + n assignment operations // variable determination outside the loop and assignment within the loop
Practice B: n constructors + n destructor // define and initialize variables in the loop
At this time, it is estimated that the cost of value assignment is low or the cost of structure + structure is low. In addition, it is worth considering the issue of object scope.

Iii. Article 27: do as little transformation actions as possible

There are usually three different forms of transformation Syntax:
1. C-style transformation: (T) expression
2. function-style transformation: T (expression)
3. The second type above is called "Old-style transformation". C ++ provides four new types of Transformation:

A: const_cast is usually used to convert the object's constant property to Division. It is also the only C ++ style transformation operator with this capability. B: dynamic_cast is mainly used to perform "secure downward transformation", that is, to determine whether certain objects belong to a type in the integration system. It is the only action that cannot be executed by the old syntax and the only transformation action that may consume significant operation costs. C: reinterpret_cast intends to perform a low-level transformation. The actual action may depend on the compiler, which means it is not portable. D: static_cast is used to force implicit conversion. For example, convert a non-const object to a cosnt object, convert an int to a double object, and convert a void * pointer to a typed pointer, convert pointer-to-base to pointer-to-derived.
C ++ provides support for the old-style transformation, but it is more recommended to use the new-style transformation because: first, they are easily identified in the code. Second, the clearer the goals of each transformation action, the more likely the compiler will diagnose the wrong application. Key points:

If possible, try to avoid transformation, especially to avoid dynamic_casts in code that focuses on efficiency. If there is a design that requires transformation, try to develop an alternative design that does not require transformation.
If transformation is necessary, try to hide it behind a function. The customer can then call the function without putting the transformation into their own code.
We would rather use the C ++-styles (New Style) transformation than the old one. The former is easy to identify and has a different role.

Iv. Clause 28: avoid returning the internal components of handles pointing to the object

If a function "returns an internal component of a handle code object" is always dangerous, whether the so-called handle is a pointer, iterator, or reference, or whether the handle is const or not, whether or not the member function that returns handle is const. The only key here is that a handle has been transferred out, And once so, you are exposed to the risk of "handle is longer than its intended object.
Key points:
Avoid returning handles (including references, pointers, and iterators) to the object. Compliance with this clause can increase encapsulation, help const member functions behave like a const, and minimize the possibility of a "virtual hanging number plate.

V. Article 29: efforts to ensure "exceptional security" are worthwhile

Abnormal security functions do not leak resources or allow any data structure corruption even if an exception occurs. Such functions are classified into three possible guarantees: basic type, strong type, and no exception type.
Strong assurance is often implemented using copy-and-swap, but "strong assurance" is not feasible or practical for all functions.
The "exception Security Guarantee" provided by a function is usually the weakest among the "exception Security Guarantee" of each function that it calls.

Vi. Terms 30: thoroughly understand inlining's internal and external

About inline:
1. the inline function is called to the function body and expands the function. improper use may result in code expansion.
2. Most of the inline functions of C ++ programs are stored in the header file. inlining occurs during compilation.
3. the inline function only represents the "function ontology". There is no "function substance" and there is no function address.

It is worth noting that:
1. constructor and destructor are often not suitable for inline. Because both functions contain many implicit calls, the cost of these calls is worth considering. Code expansion may occur.
2. the inline function cannot be upgraded with the library upgrade. Because most of them occur during the compilation phase, the upgrade means re-compilation.
3. Most debuggers cannot set breakpoints in the inline function. Because the inline function does not have an address.

Remember:
1. Most inlining restrictions are imposed on small and frequently called functions. This makes the debugging process and binary upgrade easier in the future, and minimizes potential code expansion problems, maximizing the program's speed increase.
2. In addition, exercise caution on the inline of function templates to ensure that all the implemented functions should be inlined and then inline.

VII. Article 31: Minimize the compilation and storage Relationships Between Files


This problem arises from the need to minimize the impact of compilation, improve compilation efficiency, and reduce maintenance costs.
To achieve this goal, the first thing that comes to mind is the separation of declaration and definition. Your use only depends on the declaration and does not depend on the definition (that is, the specific implementation ).
But the definition of C ++ Class is not only interface, but also implementation details (this refers to the private member required to implement the interface ). Sometimes we need to modify the implementation method of the interface, and this modification may need to add private variables, but this private variable should not be visible to users. However, this modification is placed in the header file of the definition, resulting in re-compilation of all the code of this object.
So we have the pimpl (pointer to implementation) method. Use pimpl to hide the implementation details. Only one declaration is required in the header file, and this poniter is called as a private member variable.
Here is an interesting place. Why is Pointer used instead of a specific object? This requires the compiler, because the compiler needs to know the space size of the variable in advance when defining the variable, and does not know the size if it only gives a declaration but does not define it, the pointer size is fixed, so you can define the pointer (even if only one declaration is provided ).
In this way, the Implementation Details are hidden, so the change of the implementation method will not cause the re-Compilation of some other code. In addition, only impl class declaration is provided in the header file, and the basic implementation will not be visible to users, but also increases encapsulation.

The structure should be as follows: class AImpl; class A {public :... private: std: tr1: shared_ptr <AImpl> pImpl;}; this type is also called handle class. Another implementation method is the interface class with the factory function. It is to write all interfaces as pure virtual and implement them in sub-classes, and generate instances through the factory function or virtual constructor. When declaring a file, write this statement: class Person {public: static shared_ptr <Person> create (const string &, const Data &, const Adress &);}; write the class RealPerson: public Person {public: RealPerson (...); virtual ~ RealPerson (){}//... private ://...}; the above mentioned methods used for de-coupling will inevitably carry some performance sacrifices, but the author suggests that the above methods should be used in the development process, when the above method has a greater effect on speed and/or size than coupling, write a specific object to replace the above method.

Remember:
The general idea of supporting "minimal compilation dependency" is: dependent on declarative, do not trust the definition. The two methods based on this idea are Handles classes and Interface classes.
Library header files should exist in the form of "completely and only declarative", which applies whether or not templates is involved.


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.