Effective C + + reading notes "For_wind"

Source: Internet
Author: User
Tags bitwise error handling prepare
A good book here should be read earlier. To sum up, to facilitate future inspection. For_wind
1, as far as possible to replace #define with Const,enum,inline, or as far as possible to replace the preprocessor compiler#define可能并不进入符号表 (symbol table) Const: NOTE: A, constant pointer; B, class-specific constants. Note: To ensure that class-specific constants have at most one entity, you must make it a static member.
2, as far as possible to <iostream> replace <stdio.h>
3. Replace malloc and free with new and delete as far as possibleDifferences in constructors, destructors
4, as far as possible in C + + style annotation formThat is, to use//, avoid the use of * * * * * * * * *, when the annotation block prematurely end
5, using the same form of new and deleteA, refers to the New,delete and new[],delete[] paired use. B, when you use new to dynamically generate an object, two things happen: memory is allocated; there is one (or more) constructor called for this memory, and then memory is freed (delete).       C, as far as possible not to do the array of typedef action. Summary: When you use new to generate objects, if you use new type-object[], you use delete []type-object, otherwise use the delete
6, remember in destructor with delete against pointer membersA, when there is a pointer members, the pointer is initialized or 0 in each constructor; in the assignment operator, the original memory of the pointer is removed, the piece is reconfigured, and the pointer is removed from the destructor. B, who new, who delete.     C, note the smart pointers.     Place the Newed object into the smart pointer Store newed objects in smart pointers in standalone statements as a standalone statement. The Newed object is stored in the (placed) smart pointer as a stand-alone statement. If this is not done, once the exception is thrown, it can lead to imperceptible resource leaks.
7, for the condition of insufficient memory to prepare set_new_handler.
8. The conventions to be followed when composing operator new and operator delete are required to be consistent with the default operator new (correct return value, call error handling function when memory is low, prepare to meet the "no Memory" requirement (Request 0 memory) (in fact, see     Apply 0bytes to 1bytes); it needs to be consistent with the operator delete (it is safe to delete a null pointer). More specifically, operator new should contain an infinite loop in which to attempt to allocate memory, and call New-handler if it does not meet the memory requirements. It should also be able to handle 0 bytes applications.     The class-specific version should also handle "a larger (wrong) application than the correct size." operator delete should not do anything when a null pointer is received, and the class-specific version should also handle "a larger (error) request than the correct size."
9, to avoid hiding the formal form of new and 8, you need to define class-specific operater new and invoke the default Operater new
10, if you write a operator new, please write a operator delete. Write the two together so that they can share the same assumptions. (They are mostly for efficiency and can be managed by a pool such as a linked list.)
11, if the class is dynamically configured with memory, please declare a copy constructor and a assignment operator for this classAvoid: Memory leak issues and pointer alias issues (for example, duplicate deletion and undefined issues). If you don't want to use or need to, you might as well: declare these functions private and do not define (implement) them, which prevents clients from calling them, or avoids the compiler from generating them.
12, in the constructor as far as possible initiation action (that is, Member initiation list) to replace the assignment actionBenefits: A, satisfy the const members and reference members must be initialized through the Member initiation list; B, increase the efficiency of the data members initialization (reduce function calls)
13. The Members initialization order in the initialization list should be the same as the order in which they are declared within the classNote that the class members are initialized in the order in which they are declared within the class, regardless of the order appearing in the member initialization list. (This rule is only used for initialization of the nonstatic data members.) )
14, always let the base class have virtual destructor. Avoid "Undefined behavior issues" that are generated by nonvirtual destructor. C + + clearly points out that when the derived class object is deleted through a base class pointer, and the base class takes a non-virtual destructor, the result is undefined----the actual execution occurs when the object's derived     Ingredients have not been destroyed. Method: Define a virtual destructor for base classes.     Any class with a virtual function is almost certain that there should be a virtual destructor. To implement a virtual function, an object must carry some information, primarily to determine which virtual function is invoked during the runtime.     This information is usually indicated by a so-called vptr (virtual table pointer) pointer. Having a class with a pure virtual (pure virtual) destructor causes abstract (abstract) classes---that is, the class that cannot be materialized (instantiated). Summary: polymorphic (with polymorphic properties) base classes should declare a virtual destructor.     If class comes with any virtual function, it should have a virtual destructor. The purpose of Classes is not to declare a virtual destructor if it is not used as a base Classes or for polymorphism (polymorphic).
15, make operator = return "*this's Reference"Form:c& c::operator= (const c&) {... return *this; The assignment operator must always return a reference pointing to its left argument, that is, *this. Otherwise, assignment string chains or (and) are prevented from implicit type conversions on the caller side.
16, in the operator= for all data members set (Assignment) content. When you write a copying function, make sure (1) Copy all the local member variables and (2) invoke the appropriate copying functions within all base classes.     The copying function should ensure that all member variables within the object and all base class members are replicated.     Note: Derived's copy constructor must make sure that the copy constructor of base is invoked instead of the base's default constructor. Method: Specifies the initial value for base in the member initial column of derived copy constructor. Note that the bold part should not be omitted as: Class Derived:public base{public:derived (const derived& RHS): Base (RHS), Y (rhs,y) {}}; Do not attempt to implement another copying function with one copying function. The common function should be put into a third function and called by two copying functions.
17, in the operator= check whether "oneself assign value to oneself"To ensure correctness and efficiency. An alias problem (aliasing) and an object identity problem occur: not limited to the operator= function (whenever references and pointers are present, any two object names that represent a compatible type may actually point to the same object).     Special attention must be paid to avoiding the occurrence of such problems. How to judge equality: by comparing values or by comparing addresses, you can also design and return an object identifier by using a function.
18, strive to make the interface complete (complete) and minimize the completion of reasonable work; as little as possible, without overlapping functions
19, distinguish member Function,non-member function and friend function threeVirtual functions must be class members; never let operator>> and operator<< be members.     Should be set to Non-member functions or friend (if Non-public members are used). Only Non-member functions can implement type conversion on its leftmost argument (argument).       Should be set to Non-member functions or friend (if Non-public members are used).     In this case, the member function is designed. Note: Rather take the non-member non-friend function to replace the member function. This can increase encapsulation, package elasticity, and skill expansion. If you need to type conversions for all parameters of a function (including the metaphorical argument referred to by the This pointer), then this function must be a non-member.
20. Avoid placing the data members in a public interface rather than designing a function to achieve "consistency" and excellent access control (using "function abstraction").
21. Use const as much as possibleA, if the keyword const appears to the left of the asterisk, the indicated type is a constant, and if it appears to the right of the asterisk, the pointer itself is a constant, and if both sides of the asterisk denote the type and the pointer are both constants. B, the most representative of Const is the application of function declaration. The const can be associated with function return values, parameters, functions themselves.     C, CONST member functions: 1 They make the class interface relatively easy to understand. 2 They make it possible to "manipulate the Const object". D, if the return type of the function is a built-in type, then it is not lawful to modify the function return value. E, bitwise constness (physical constness) member functions can be said to be const only if you do not change any of the object's member variables (except static). That is, it does not change any bit (bit) within an object.     F, Logical constness A const member function can modify some bits within the object it handles, but only if the client cannot detect it.       mutable (mutable) keywords can release the bitwise constness constraints of non-static member variables; G, avoid duplication in the const and NON-CONST member functions, and let the latter invoke the former if possible The const member function calls the Non-const member function is an error behavior because the object may be altered accordingly.
22, as far as possible use pass-by-reference (address), less use Pass-by-value (transfer value)Try to replace pass by value with pass by reference. The former are usually more efficient and can avoid Cutting Problems(slicing problem). However, it does not apply to built-in types, as well as STL iterators and function objects.       For them, pass by value is often more appropriate.       If you have an object that belongs to a built-in type (for example, int), pass by value is often more efficient than pass by reference. Also, pass by reference you need to pay extra attention to avoiding alias problems.
23, when you must return object, do not try to return reference remember: Reference is a name of an existing object. Note the possible memory leak problem.
24. Consider carefully between function overloading and parameter defaults: A, whether the appropriate values can be used as default parameters; B, how many algorithms.
25, to avoid the pointer type and numeric type overload mode of the ambiguous.
26, the defensive latent ambiguity state "access restrictions" can not relieve the "more inherited from the members" of the model of the ambiguous state. (Reason: Changing the accessibility of a class member should never change the meaning of the program.) )
27, if you do not want to use the compiler secretly generated by the member functions, it should be clear to reject it. Private, empty. You can customize the functions that the compiler will generate by default, either manually as private, or by declaring null functions using an empty base class (empty base classes).
28. Try to cut global namespace using
29, to avoid the return of internal data handlesProblem: Violation of abstraction, there are dangling handles and alias problems.
30, to avoid writing member functions, return a non-const pointer or reference and point to the lower access level membersProblem: Damage access protection, prone to alias problems.
31, do not return "the function within the local object's reference" or "function within the pointer to get the object"Problem: Undefined behavior, memory leak
32, as far as possible to delay the emergence of variable definitionThat is, it is necessary to define, avoid constructing (and destructors) Non-essential objects, and avoid meaningless default constructors. In addition, it can increase the clarity of the program and improve the efficiency of the program.
33. Use inlining wiselyA, inline, just a hint to the compiler, and not a mandatory command。 means that the invocation action is replaced by the ontology of the invoked function at compile time, and whether it is really inline, depending on the compiler. Most compilers will RejectA complex (that is, a loop or recursive call) function is inline, and all (except the most mundane, almost nothing) of the virtual function will prevent the inlining. B, weighing the cost of calling the function, and the increase in the size of the program code. Benefits: The function body of the inline function is small, smaller target code and higher cache hit ratio; Cost: eliminates the cost of function calls, but may increase the size of the target code. Inline behavior caused by the expansion of the program code will lead to a pathological change of page behavior (thrashing phenomenon). The inline function cannot be upgraded as the library is upgraded, and if the function has a static object that has a counter-intuitive behavior, it is generally avoided to declare it as inline, and most of the debugger is helpless against the inline function C, limiting most inlining to small, On functions that are called frequently. This makes future debugging and binary upgrades (binary upgradability) easier, and minimizes potential code bloat problems, maximizing the speed of the program. Do not declare the function templates as inline only because they appear in the header file.
34. Minimizing compilation dependencies between files support the general idea of minimizing "compile dependencies" is to rely on the declaration and not on the definition. The two means based on this idea are handle classes and interface classes. The library header file should exist in the form of full and declearation-only forms. This practice applies whether or not the templates are involved
35, determine your public inheritance, molded out "is a" relationshipC + + (OOP) object-oriented programming, the most important rule is: public inheritance (open inheritance) means "is-a" (is a) relationship. If you make class D ("derived") Inherit class B ("Base") as public, you tell the compiler that each object of type D is also an object of type B, and vice versa. "Pubilc inheritance" means is-a. Everything that applies to base classes must also be used for Derived classes, because each Derived class object is also a base class object.


36. Differentiate interface inheritance and implement inheritance differentiate between inheritance of interface and inheritance of implementation pure virtual functions, general (impure) virtual functions, non-virtual functions Allows you to specify exactly what you want derived class to inherit: simply inherit the interface, or inherit interfaces and default behavior, or inherit interfaces and an implementation code. Interface inheritance differs from implementation inheritance. Under Pubilc inheritance, derived classes always inherits the interface of base class. The Pure virtual function specifically specifies interface inheritance. The impure virtual function specifies interface inheritance and default implementation inheritance. The Non-virtual function specifically specifies interface inheritance and mandatory implementation inheritance.
37, never redefine an inherited non-virtual function.
38, never redefine the inherited default parameter values. Because the virtual function (the only thing you should copy) is dynamic binding (depending on the type that the pointer or reference points to), and the default parameter value is statically bound (depending on the pointer or the static type of the reference).
39, avoid in the inheritance system to do downward transformationDownward transition downcast: from a "base class pointer" to a "derived class pointer". Problem: Code is difficult to understand and difficult to maintain. Workaround: Replace the transformation action with the call of the virtual function, and have each virtual function have a default implementation code without any action to apply to any classes that do not want to implement the virtual function.
40, through the laying technology to molding has-a or is-implemented-in-terms-of relationshipA composite (composition) is a relationship between types, which is the case when a type of object contains its type of object.
Notice the difference between the two. Reuse.
41. Distinguish Inheritance and templatesInheritance is used to produce a group of classes, in which object types affect the function properties of class. Templates are used to produce a group of classes, where object types do not affect the function properties of class.
42. Use private inheritance wiselyIf the inheritance relationship between classes is private, the compiler does not automatically convert a derived class object to a base class object. All members inherited from private base class become private in the derived class.
43. Using Multiple Inheritance wiselyMultiple inheritance caused by the problem: the model Ling ambiguous ambiguous. Multiple inheritance is more complex than single inheritance.      It can lead to new ambiguity and the need for virtual inheritance.     Virtual inheritance increases the cost of size, speed, initialization (and assignment) complexity, and so on.     Workaround: You can try to inherit a newly added public base class together. Multiple inheritance does have a legitimate purpose. One of these episodes involves a two-phase combination of "public inheriting a interface class" and "private inheriting one of the help-implemented classes"
44. Say what you mean and understand every word you say.The common base class means a common attribute.     If class D1 and D2 both declare Class B as base, then D1 and D2 inherit the common data members and member functions from B. Public inheritance (open inheritance) means "is a (ISA)".        If Class D inherits class B as public, then each D object is a B object, not the other way up. Private inheritance (proprietary inheritance) means "implement (is-implemented-in-terms-of) according to something."     If Class D inherits the class B,d object in private, it is implemented according to D, and there is no conceptual relationship between the B object and the D object. Layering means "have one (has-a)" or "achieve (is-implemented-in-terms-of) according to something."     If Class A contains a data member of type B, then there is an element of type B in object A, or a object is implemented according to a B object.     ----Only when it comes to public inheritance, a few points are set up:---see 36. A pure virtual function means that only its function interface is inherited.     If Class C declares a pure virtual function MF, then C's subclasses must inherit the MF interface, and C's representational subclasses must provide its own implementation code. A generic (impure) virtual function means that both the function interface and the default implementation code are inherited.     If Class C declares a generic (impure) virtual function Mf,c subclasses must inherit MF's interface, they can inherit MF's default implementation code (if they decide to do so). A non-virtual function means that both the interface of this function and its implementation code are inherited. If Class C declares a non-virtual function MF, then C's subclasses must inherit both the MF interface and the implementation code. In fact, MF defines a property of "invariance above variability" for C.
45, understand C + + silently write and call which functionsC + + Adds the default constructor default constructor for the null class (empty Class), Copy constructor constructor destructor destructor assignment assignment operator and a pair of address-of Address Value operators Note: Only when these functions are invoked will they be created by the compiler. For the assignment assignment operator, the following conditions refuse to produce a default operator=, and you must set a assignment operator. A, "contains reference member"; B, contains const MEMBERS;C, base class to declare the assignment operator private.
46, prefer to compile and connect error, do not execute when the wrong
47, using non-local static objects before the line to determine that it has an initial valueThe singleton pattern technique is used to replace non-local static objects with static objects in function. Initializes the definition of this object for the first time during this function call period.
48, do not see the compiler's warning information as seen.
49, try to familiarize yourself with the C + + standard library
50, to strengthen their understanding of C + +

Here is the third version of the new add, understand. “。。 "The department did not fully understand
--21 more--const_castUsage:const_cast<type_id> (expression) This operator is used to modify the const or volatile properties of a type. The constant pointer is converted to a very pointer and still points to the original object; The constant reference is converted to a very literal reference and still points to the original object; The constant object is converted to a very object;static_castUsage:static_cast<type_id> (expression) This operator converts expression to Type-id type, but does not have run-time type checking to guarantee the security of the conversion.  C + + Primer is explained in the implicit type conversion with Int I = static_cast<int>f; float F = 1.42f;

---clause 04: Determines that the object has been initialized before it is used to make sure the are initialized befor they ' re used.
Reading an uninitialized value can result in ambiguous behavior.
When the initialization of an object must occur and when it does not occur. For built-in types without any members, you must do this manually. For anything other than the built-in type, the initialization responsibility falls on the constructor (constructors). Make sure that each constructor initializes each member of the object. C + + rules,The initialization action of the member variable of the object occurs before entering the constructor ontology。 The best method for constructing a constructor is tousing the Member initialization list (Members initialization table)such as: Abentry::abentry (char &name,char& address,list &phones): thename (name), theaddress (address), Thephones (phones) { ....... } The compiler automatically invokes the default constructor for the member variables of the user-defined type (user-defined types)---if those member variables are not specified in the member initialization list.member variables are const or references, they must have initial values and cannot be assigned。 C + + has a very fixed "member initialization order." Base classes is initialized earlier than its derived classes, and class's member variables are always initialized in their declaration order.   A Static object whose active time is constructed until the end of the program, so that the stack and heap-based objects are excluded.     C + + has no clear definition of the initialization relative order for "non-local static objects defined in different compilation units." Small method: Place each non-local static object inside its own exclusive function (which is declared static within this function) that returns a reference to the object it contains. Summary: Manual initialization of built-in objects because C + + does not guarantee initialization of them. Constructors are best to use the Member initialization list (initialization) instead of using assignment operations (Assignment) within the constructor ontology. To exempt the "initialization order across compilation units" issue, replace the non-local static object with the local static object.
-------clause 09: Never invoke the virtual function during construction and destructor

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.