Effective C + + terms 26-31 "class and function implementation" collation

Source: Internet
Author: User

I. Problems facing the implementation of the class:

Too fast to define variables can cause efficiency delays; over-use transformation (casts) can cause code to be slow and difficult to maintain, and to attract subtle and difficult errors; return object "internal data of the number plate (HANDLS)" may break the package and leave the customer virtual hanging number card ; To consider the impact of anomalies can lead to resource leaks and data corruption; overly zealous inlining may cause code bloat; Over-coupling can lead to tedious build-up times that are unsatisfactory.

II. Clause 26: Delay the occurrence of variable definitions whenever possible

Some objects, you may define it prematurely, and in the course of code execution, lead, resulting in the beginning of the definition of the object has not been used, and paid the structure of the original analysis.
So we should try to postpone the definition of the object as long as possible, even until we have to use the variable, until we can give it an initial argument.
The advantage of this is that you can avoid not only constructing (refactoring) non-essential objects, but also avoiding meaningless default construction behavior.
What happens when I run into loops? Often we will have two choices at this point:
Procedure A: A constructor + 1 destructors +n Assignment Operations//variables outside the loop, assigning values within a loop
Procedure B:n A constructor +n a destructor//define and initialize the variable within the loop
At this time to estimate the cost of the assignment is low or the construction + destruction of low cost, it is also worth considering the object scope of the problem.

III. clause 27: as little as possible to do transformational action

The transformational syntax usually has three different forms:
1,c Style of Transformation: (T) expression
2, Function Style transformation action: T (expression)
3, the second of the above is called "legacy transformation", and C + + offers four new types of transformation:

A:const_cast are often used to remove the constants of an object. It is also the only C + + style transformation operator that has this ability. B:dynamic_cast is primarily used to perform a "security down transition", which is used to determine whether certain objects belong to a type in the integration System. It is the only action that cannot be performed by legacy syntax, and is the only transformational action that can cost significant operational costs. C:reinterpret_cast intent to perform a low-level transformation, the actual action may depend on the compiler, which means that it is not portable. D:static_cast is used to force implicit conversions, such as converting an Non-const object to a Cosnt object, converting an int to a double, and a void* pointer to a typed pointer. Convert Pointer-to-base to pointer-to-derived and so on.
C + + provides support for legacy transformations, but it is more recommended to use the new transformation because: first, they are easily identified in the code. Second, the more explicit the goal of each transition action, the more likely the compiler is to diagnose the wrong application. Points:

If you can, try to avoid the transition, especially in the efficiency-focused code to avoid dynamic_casts. If you have a design that requires transformational action, try to develop an alternative design that doesn't need to be transformed.
If transformation is necessary, try to hide it behind a function. The client can then invoke the function without having to put the transformation into their own code.
Rather than using c++-styles (new) transformation, don't use legacy transformations. The former is very easy to identify, but also a comparative necromancy.

IV. Clause 28: Avoid returning handles to the inner component of the object

function if "Return a handle Code object internal component" is always dangerous, whether the so-called handle is a pointer or an iterator or reference, and whether the handle is a const or not, and whether the member function that returns handle is const. The only thing that matters here is that a handle has been handed out, and once that happens, you are exposed to the risk that "handle is longer than the object it refers to".
Points:
Avoid returning handles (including references, pointers, iterators) to the inside of the object. Adherence to this clause increases encapsulation, helps the const member function behave like a const, and minimizes the likelihood of a "virtual lift number card" occurring.

V. Clause 29: It is worthwhile to work for "exceptional safety"

The exception security function does not leak resources or allow any data structures to corrupt, even if an exception occurs. Such a function area is divided into three possible guarantees: basic type, strong type, non-throwing anomaly.
Strong assurances can often be achieved with copy-and-swap, but "strong assurances" are not achievable or meaningful for all functions.
The "Exception security guarantee" provided by the function is usually the highest of the weakest in the exception security guarantee for each function that it invokes.

Vi. Article 30: A thorough understanding of the inside and outside of inlining

About Inline:
1. The invocation of the inline function is the invocation of the function body, which is the expansion of the function, which causes the code to swell with improper use.
2. The inline function of most C + + programs is placed in the header file, inlining occurs at compile time.
3. The inline function represents only the "functional body", and there is no "function substance", there is no function address.

It is worth noting that:
1. Constructors and destructors are often unsuitable for inline. Because both functions contain many implicit calls, the cost of these calls is worth considering. There may be a case of code bloat.
2. The inline function cannot be upgraded with the library upgrade. Because most of them occur at compile time, the upgrade means recompiling.
3. Most debuggers cannot set breakpoints in the inline function. Because the inline function does not have an address.

Please remember:
1. Most inlining are limited to small, frequently called functions. This makes future debugging and binary upgrades easier, as well as minimizing potential code bloat issues, maximizing the chances of a program's speed increase.
2. In addition, the templates of the function is also prudent, ensuring that all of its implemented functions should be inlined and then added inline.

VII. clause 31: Minimizing compilation and storage relationships between files


This problem arises from the need to minimize the scope of the compile-time impact, compile more efficiently, and lower maintenance costs.
The first thing that comes to mind in achieving this goal is the separation of the declaration from the definition, and the user's use depends only on the declaration, not on the definition (that is, the implementation).
But the C + + class definition is not just an interface, but also a implementation detail (this refers to the private member that implements the interface). And sometimes we need to modify the implementation of the interface, which may need to add a private variable, but this private variable should not be visible to the user. However, this modification is placed in the header file of the definition, resulting in the recompilation of all the code that uses this one-end file.
Then there is the method of Pimpl (pointer to implementation). Using Pimpl to hide the implementation details, only one declaration is required in the header file, and this poniter is used as the private member variable for invocation.
There's an interesting place here, why use pointers, not concrete objects? This is a question for the compiler, because the compiler needs to know the spatial size of the variable in advance when defining the variable, and if it is not known for a declaration but not defined, the pointer size is fixed, so you can define the pointer (even if only one declaration is provided).
This hides the implementation details, so that changes to the implementation method will not cause any other part of the code to be recompiled. and the header file only provides declarations of the Impl class, and the basic implementation is not visible to the user, but also adds encapsulation.

The structure should be as follows: Class Aimpl;class A {public:    ... private:    std::tr1::shared_ptr<aimpl> Pimpl;}; This kind is also called handle class. Another way to implement this is to use the interface class with the factory function. is to write the interface into pure virtual, the implementation is in the subclass, through the factory function or virtual constructor to produce an instance. When declaring a file: Class Person{public:    static shared_ptr<person> Create (const string&,        const data&        const adress&);}; Define the implemented file so write class Realperson:p ublic person{public:    realperson (...);    Virtual ~realperson () {}    //...private:    //...}; The above-mentioned approach to decoupling will inevitably lead to some performance sacrifices, but the authors suggest that the above method should be used in the development process, and when the above methods have a greater effect on speed and/or size than on coupling, then write specific objects to replace the above methods.

Please remember:
The general idea of supporting the minimization of compilation dependencies is that it is dependent on the declarative, not the definition. The two instruments based on this conception are handles classes and interface classes.
The library header file should be in the form of "full and declarative Only", which is applicable regardless of whether templates is involved.


Effective C + + terms 26-31 "class and function implementation" collation

Related Article

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.