"Effective C + +" Reading notes summary

Source: Internet
Author: User
Tags define function traits

Before I read "effective C + +", I wrote the reading notes for each article, which was the previous version of C++11. Here I have a summary of each of the terms that impresses me a little bit.

1. C + + includes: Plain C (process-oriented), OOP (object-oriented), templates (generics and template metaprogramming), STL (c + + standard library).

2. Use inline, enum, and const instead of # define. #define定义的宏, once complex, the master is very difficult to control. Don't get into C's habit.

3, flexible use of the const prefix. Data that does not need to be changed is prefixed with a const. The const prefix of a pointer has two forms, and the const is placed on the left to indicate that the data is unchanged, and the right side indicates that the pointer address is unchanged. The member function that returns member data that does not need to be modified requires a const token.

4. Ensure initialization before using the object. Simple built-in data structure (POD), some compilers are directly initialized to 0. A custom data structure, especially one that contains pointers, is preferable to a well-defined initialization procedure that assigns a pointer to a value of 0 or null.

5. Understand what functions C + + secretly wrote and called. The class automatically generates the default constructor, the copy constructor and the copy assign function, and if the copy constructor is not explicitly defined, then the copy of the class object is copied with only a shallow copy operation, which may not match the original intent. Therefore, these functions need to be explicitly defined so that the C + + compiler is not automatically generated.

6. You can refuse to use the compiler-generated default functions. The method is to put these default functions into private, so that the program will not be able to use the default function.

7. Declare the virtual destructor for the polymorphic base class. If the base class does not define a virtual destructor, then when we point to the derived object with a base-class pointer, the derived object is refactored through the base-class pointer, and the destructor of the derived object cannot be called . So you want to write a virtual destructor for the base class beforehand so that both the base class and the derived class perform the destructor. STL is not a complete object-oriented idea, for example, there is no virtual destructor, so it is not possible to implement polymorphism with STL class as base class.

8. Do not let the exception escape the destructor. Before handling the exception, make sure that the resources are refactored, otherwise there will be a resource leak caused the bug, if not, then terminate the program is the most insurance method. A feasible way to ensure resource destruction use resource management classes or smart pointers to manage resources.

9. Never call the virtual function in the construction and destruction. When a derived instance is constructed, the base construction part invokes the virtual function, and the virtual function of the base class is called instead of the virtual function of the derived class.

10, make operator= return a reference to *this. This is the standard, many people will forget.

11. Handle "Self-assignment" in operator=. Judging whether the parameter is itself, if it is itself, return directly, do not do useless things.

12, copy the object do not forget any one ingredient. Because forgetting to copy objects is not a warning or a mistake, it is written carefully by the developers themselves.

13. Manage resources with objects. Because there is no resource disclosure problem with the basic data type, we can define the behavior of the object so that it is similar to the basic data type. Let the object manage resources so that the object behaves like a basic data type, so that you can manipulate the custom object like a basic data type. Resource management classes and smart pointers are two common resource management objects.

14, in the resource management class carefully coping behavior. The resource management class can have four kinds of coping behavior: a prohibits copying, such as the Uncopyable Class B reference count that inherits boost, and does not copy resources just add a reference, such as smart pointer C copy Resource D transfer rights, such as std::auto_ptr, less use.

15. Provide access to the original resource in the resource management class. The optimal design of the resource management class is to make the resource management class use the same as the basic data type. It is necessary to design a good interface to access the raw resources encapsulated by the resource management class.

16, the use of new/delete into the same form. If you use new, delete is used, and if you use new [], delete [] is used, and if you request a resource with malloc, use the free to deconstruct the resource.

17. Place the Newed object into a smart pointer with a separate statement. Processwidget (std::tr1::shared_ptr<widget> (new Widget), priority ()), there are three operations: 1, New Widget2, construction SHARED_PTR3, The priority function. The compiler is unsure of the execution steps above, so if the execution order is exactly such 1, new Widget2, priority function 3, construct shared_ptr. If an exception is thrown when the priority function is executed, then the construction shared_ptr does not occur, and the widget leaks.

18, make the interface easy to use correctly, not easy to misuse. Design interface behavior is best consistent with built-in data types.

19. Design class is like design type. Design needs attention: 1, create and destroy 2, initialization and assignment is different 3, how to copy 4, error checking 5, inheritance Relationship 6, type conversion 7, what legal behavior 8, explicitly deny using some function 9, member data access operation Interface 10, whether to use template generalization 11, How do I handle a property without an interface? 12, need to design such a class.

20, try to use the const reference pass instead of value delivery, to pass the non-modifiable data. If it is a basic data type, there is no difference between value passing and const reference passing. If the data passed is large, then value passing consumes a lot of work on the construction of replicated data.

21, you must return to the object, do not be paranoid to return to its reference. The local scope object must return a value and cannot return a reference because the program is running out of scope and the local object is automatically refactored.

22. Declare the member variable as private. Follow the packaging principles of OOP. In the test and debugging can actually be temporarily flexible.

23, Ning can Non-member, non-friend replace member function. The use of non-member functions avoids miscellaneous classes and is more extensible. See article 24 for the second reason.

24. If all parameters require type conversion, use the Non-member function. The binocular overloaded operator member function can only type-convert the second argument. Overloaded binocular operators are non-member functions that allow you to type-convert pre/Post-op objects.

25. Consider writing a swap function that does not throw an exception. Swap is used to efficiently exchange data from two of objects, using a lot of techniques inside, multiple swap can increase the speed of the program, and if the swap function is robust and does not throw an exception, then the program is much more robust.

26, as far as possible delay the occurrence of variable-definition time. Standard C requires a variable to be defined at the beginning of the program. In C + +, you can define variables when you want to use the data, which facilitates the development of the program.

27, as little as possible to do transformation operations. Transformational operations change data, making it easy for developers to write bugs.

28. Avoid returning handle points to the inner component of the object. Use the data access operation functions provided by the class, and do not return references, pointers, iterators directly.

29. It is worthwhile to work for exceptional safety. Exception security has two conditions: 1, does not disclose resources 2, does not allow the impact of other data. There are three exception security levels: 1, basic commitment: throws an exception, but the program can still be used. But the current state is unknowable 2, strongly guaranteed: throws an exception, the program state is unchanged. If success is successful, rollback to original state 3, without throwing an exception, is absolutely successful if it fails. In most cases, the first two exception security levels need to be guaranteed; swap is guaranteed to be a third level.

30, thoroughly understand the inside and outside of inlining. The inline function expands to the call, equivalent to a high security # define function, the inline function can be pre-declared, the inline function is placed in the header file, and the function in the class, if placed in the header file, is the inline function; The inline function can be templated The inline function cannot be a virtual function; The inline function is a small function, which causes the program to swell if the scale is too large.

31, minimize the compilation dependencies between files. Maintain low coupling between modules, using Pimpl technology, pointer to the implementation module, which separates the implementation from the interface.

32. Make sure your public inheritance shapes the is-a relationship. D is inherited from B, then D is a special case of B, where b can be used, and D can also.

33. Avoid concealing the inherited name. If you overwrite the available function foo in the base class, the effect of using B.foo and using D.foo is different, and it is possible that the B can be used where D is unusable.

34, differentiate interface inheritance and implement inheritance. 1. The Non-virtual function indicates that the function is inherited and does not have to be changed, which is the interface + enforcement inheritance 2, and the pure virtual function indicates that only the interface is inherited. 3. Impure virtual function represents the inheritance interface and the default implementation

35. Consider a method other than the virtual function interface. Virtual functions can be automatically called according to the Class 1, non-virtual function interface (NVI) interface is not virtual function, call virtual function, security is better, you can inherit the default parameter 2, function pointer, similar to the method of Delegate 3, C++11 Std::function method, you can use ordinary functions, function objects, member functions , Lambda is treated like a function pointer to object 4, the policy design model

36. Do not redefine the inherited non-virtual function. A non-virtual function is an interface + implementation inheritance, which in principle cannot be redefined, and also to ensure that the local derived classes used by the base class can also be used, and that the base class's own non-virtual functions cannot be redefined.

37. Do not redefine inherited default parameters. 36 shows that non-virtual functions cannot be redefined, so the default parameters are best not modified; For virtual functions, because virtual functions are dynamic bound, the default parameters are static bindings, so the default function is not dynamic, such as derived class D inherits base class B, class b{public:virtual void foo (int i = ten) {printf ("B:%d", i);}}; Class d:public b{public:virtual void foo (int i = +) {printf ("D:%d", i),}};, now has a class B pointer to D, call B.foo () actually calls foo (inti = 10) { printf ("d:%d", I);}.

38, through the composite mold out has-a or "according to something to achieve." Has-a represents the composition of class C through the embedded Class D to achieve a certain function, C contains D; can be analogous to the composite pattern in design patterns.

39. Use private inheritance wisely and prudently. Private inheritance is the implementation of inheritance, do not inherit the interface, the comparison is difficult to navigate. General use of public inheritance + composite or pimpl to replace private inheritance.

40. Use multiple inheritance wisely and prudently. Multi-inheritance is difficult to control, can use single inheritance and other modes, do not use multiple inheritance; multiple inheritance will cause unnecessary loss of large-scale system, and result in program volume expansion and performance degradation.

41, understand the implicit interface and compile-time polymorphism. The template type of the template class T, although not clear about the type of T, but the actual use of the interface may use T. If T does not have a given interface, it will be error-free at compile time.

42, understand the dual meaning of TypeName. TypeName and class can be used when representing a template. If you use the internal definition of a template type, you need to add TypeName. t::const_iterator it1 = ...// Compile Error typenamet::const_iterator it2 = ....// correct

43. Learn the name within the base class of the processing template. The template class d<t> inherits the template base class B<t> If you use the B function directly in D, the compiler may error. This is the time to explicitly indicate the function we use b<t>: Usingb<t>::foo;foo () or b<t>::foo ()

44. Extract the parameter-independent code from the template. Assuming that Class D has two template parameters <t,u>, and that each template parameter may have 4 choices, then the compiler will implement all the template classes, producing 4*4=16 classes. If the implementation of class d<t,u> can be divided into classes b<t> and C<u>, the compiler produces classes that have 4 B, 4 C and 4 D, and only 12 classes. If the template parameters are selected more, the resources saved in this way are more obvious.

45. Use the member function template to accept all compatible types. There are two types of templates available for class and member templates. The method is similar to 44 bars.

46. Define a non-member function for the template when a type conversion is required. Reason for the same 24.

47. Please use the Traits class expression type information. The traits technique is that the program invokes a function against the class based on the type of member inside the class. Traits technology replaces the traditional method of the If Judgment statement +typeid function, and instead uses the compiler to select the appropriate processing function. This kind of method is widely used in STL programming, also known as type-trait technology.

48, know the template meta-programming. Refers to the writing of a class of computer programs, which write or manipulate other programs (or themselves) as their data, or at run time to complete some of the work that should be done at compile time, template meta-programming often achieve the latter. The advantages of template metaprogramming include: 1 transfer of work from the runtime to the compile time, making it easier to discover that 2 executables consume less memory and run short. The disadvantage has 10 minutes of lengthy compilation time 2 is difficult to use, known as "College School programming."

49, understand the behavior of New-handler. When the heap allocation function operator new allocation error, it will invoke an error handler, which can be a user-specified function, which is the New-handler,new_handler function no return value, no parameters, it is generally best to throw an exception. When the operator new function fails, no memory is applied, and the New_handler function is constantly called, knowing that enough memory is found. Therefore, a new_handler function that does not do anything can cause abnormal behavior such as suspended animation of the program. The normal New_handler function can choose to do the following things: 1 release other memory, provide free memory 2 install another new_handler, do something else according to the actual situation 3 throw Bad_alloc Exception 4 call abort or exit.

50, understand the new and delete reasonable replacement time. Scenarios using custom new and delete: 1 detecting and outputting error 2 hardening performance at debug time. Typical is memory pool technology, which reduces memory fragmentation, reduces application space and frees up space by 3 to collect memory run information. Common program apes it is difficult to write efficient and versatile memory management tools, typically using well-known open source tools or buying commercial libraries.

51, write new and delete must adhere to the general. New and delete have regular common standard patterns.

52, wrote placement new also to write placement delete. If we write a custom placement new function that results in an error, the system calls the placement delete function to free up space. If we write placement new without writing the placement delete function, then the system will not be able to free up space to know

53, do not easily ignore the compiler warning. The compiler's warning is not necessarily a simple question: If some code is really wrong with your original intent, but the compiler can simply follow other semantics to make it compile, it's hard to find the error. GCC is good at the ISO C + + standard, and at the highest GCC warning level, write code without warning, which can basically be compiled on any platform's C + + compiler.

54, familiar with the standard program library including TR1. Prior to the official version of C++11, c++11 some of the features have been encapsulated in newer compilers, such as VS2008SP1 's TR1 module. Most of the other modules that are not formally included in the C++11 standard are stored in the boost library. These quasi-standard libraries can greatly reduce workload.

55, familiar with boost. If you've already started using the C++11 standard, you'll find a lot of things familiar in the boost library. No standard modules are included in the boost library and can be used in many open source environments, and it is prudent to use the boost library in a high-intensity industrial environment.


"Effective C + +" Reading notes summary

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.