Effective C + + 55 and things to remember

Source: Internet
Author: User
Tags traits

1. Make yourself accustomed to c++01. Depending on C + + as a language federation, remember:
c++ the code of effective programming varies depending on what part of C + + you use
02. Try to replace # define with Const,enum,inline, remember:
 For simple variables, it is best to replace #defines with a const object or enums
 For macros that resemble functions (macros), it is best to replace #defines with the inline function instead
03. Use the const as much as you can remember:
 Declaring something as const can help the compiler detect incorrect usage. A const can be applied to objects, function arguments, function return types, and member function bodies within any scope.
 The compiler enforces bitwise constness, but you should use "Conceptual constants" (conceptual constness) when you write programs
 When const and NON-CONST member functions have a substantially equivalent implementation, making the NON-CONST version call the const version avoids code duplication
04. Make sure the object is initialized before it is used remember:
 Manual initialization of built-in objects, because C + + does not guarantee that they are initialized.
The constructor is preferable to use the Member initialization list (member initialization list) instead of using the assignment operation (assignment) within the constructor body. Initialize the list of member variables, which should be in the same order as they are declared in class.
 To exempt the "initialization Order of cross-compilation units" issue, replace the non-local static object with the local static object
2. Construction/destructor/assignment Operation 05. Learn what functions C + + silently writes and calls, and remember:
 The compiler can secretly create default constructors, copy constructors, copy assignment operators, and destructors for class
06. If you do not want to use the compiler automatically generated functions, the explicit rejection please remember:
 To dismiss the function provided by the compiler automatically (secretly), the corresponding member function can be declared private and not implemented. Using a base class like uncopyable is also a practice.
07. Declaring a virtual destructor for a polymorphic base class remember:
polymorphic (with polymorphic) base classes should declare a virtual destructor. If class has any virtual functions, it should have a virtual destructor.
The purpose of classes is not to declare a virtual destructor if it is not used as base classes, or not for polymorphism (polymorphically).
08. Don't let exceptions escape destructors remember:
The destructor must never throw an exception. If a function called by a destructor might throw an exception, the destructor should catch any exceptions and then swallow them (not propagate) or end the program.
 If the customer needs to react to an exception thrown during an operation function, then class should provide a normal function (rather than a destructor) to perform the operation.
09. Never call the virtual function in the construction and destruction process, remember:
 Do not call the virtual function during construction and destruction, because such calls never fall to derived class (compared to the layer that currently executes constructors and destructors)
10. Make operator= return a reference to *this please remember:
 The assignment (Assignment) operator returns a reference to *this.
11. In operator=, handle "self-assignment" remember:
 Ensure that operator= has good behavior when the object is self-assigned. The techniques include comparing the addresses of "source objects" and "target objects", the thoughtful sequence of statements, and Copy-and-swap.
 Determine if any function operates more than one object, and if more than one object is the same object, its behavior is still correct.
12. Do not forget each ingredient when copying objects remember:
The copying function should ensure that all member variables within the object and all base class components are copied.
 Do not attempt to implement another copying function with one of the copying functions. Common functions should be put into the third function and called together by two copying functions.
3. Resource Management 13. Managing resources with objects Remember:
 To prevent resource leaks, use the Raii object, which obtains resources in constructors and frees resources in destructors.
 Two commonly used RAII classes are tr1::shared_ptr and auto_ptr respectively. The former is usually a better choice, because its copy behavior is more intuitive. If you select Auto_ptr, the copy action will cause it (copied) to point to null.
14. Be careful about copying behavior in the resource management class remember:
 The replication Raii object must replicate the resources it manages, so the copying behavior of the resource determines the copying behavior of the Raii object.
 General and common RAII class copying behavior is: Suppress copying, execute reference counting method (reference counting). But other behaviors can also be achieved.
15. To provide access to the original resource in the resource management class, remember that:
apis often require access to raw resources, so each RAII class should provide a way to "get the resources it manages".
 Access to the original resource may be transformed by a display or by an implicit conversion. Generally speaking, conversion is more secure, but implicit conversion is more convenient for customers.
16. Use the same form when using new and delete in pairs, remember:
 If you use [] in the new expression, you must also use [] in the corresponding delete expression. If you do not use [] in the new expression, you must not use [] in the corresponding delete expression.
17. Place the Newed object into a smart pointer with a separate statement remember:
 The Newed object is stored in the (placed) smart pointer in a separate statement. If you do not, once an exception is thrown, it is possible to cause an imperceptible resource leak.
4. Design and declaration 18. Make the interface easy to use correctly, not easy to misuse please remember:
 Good interfaces are easy to use correctly and are not easily misused. You should strive to achieve these properties in all of your interfaces.
The "promote proper use" approach includes interface consistency and compatibility with built-in types of behavior.
 The "block misuse" approach includes establishing new types, restricting operations on types, constraining object values, and eliminating customer resource management responsibilities.
The TR1::SHARED_PTR supports custom deleter. This can prevent DLL problems and can be used to automatically unlock the mutex (mutexes; see clause 14) and so on.
19. The design class is like the design type, remember:
The design of class is the design of type. Before you define a new type, make sure that you have considered all the discussion topics covered by this article.
20. Pass-by-reference-to-const instead of Pass-by-value please remember:
 Try to replace Pass-by-value with Pass-by-reference-to-const. The former is usually more efficient and avoids cutting problems (slicing problem).
 The above rules do not apply to built-in types, as well as STL iterators and function objects. For them, pass-by-value tend to be more appropriate.
21. When you must return an object, don't be paranoid about returning to its reference remember:
 Never return pointer or reference point to a local stack object, or return reference point to a Heap-allocated object, or return pointer or reference to a local A static object may require multiple such objects at the same time. Clause 4 provides a design example for "reasonably returning reference to a local static object in a single-threaded environment."
22. Declare the member variable as private remember:
 Remember to declare the member variable as private. This gives the customer access to data consistency, fine-grained access control, assurance of promise constraints, and provides class authors with full flexibility.
protected is not more encapsulated than public
23. Instead of replacing the member function with Non-member,non-friend, remember:
 Instead of replacing the member function with the Non-member non-friend function. This can increase encapsulation, wrap elasticity (packaging flexibility), and functional expandability.
24. If all parameters require type conversion, please use the Non-member function to remember:
 This function must be a non-member if you need to convert all parameters of a function, including the metaphor parameter referred to by this pointer.
25. Consider writing a swap function that does not throw an exception, remember:
 When the std::swap is not efficient for your type, provide a swap member function and make sure that the function does not throw an exception.
 If you provide a member swap, you should also provide a non-member swap to invoke the former. For classes (not templates), please also special std::swap.
 You should use the using declaration for std::swap when calling swap, and then call swap without any "namespace qualification adornments"
 Std templates for "User Defined type" is good, but don't try to add something new to STD in Std.
5. Implementation 26. Delay the occurrence of variable definitions as far as possible remember:
 Delay the emergence of variable definitions whenever possible. This can increase the clarity of the program and improve the efficiency of the program.
27. Do as few transitions as you remember:
 If possible, avoid transformation, especially in the efficiency-oriented 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 use C++-style (new) transformation, do not use the old-fashioned transformation. The former is very easy to identify, but also a comparative necromancy.
28. Avoid returning handles point to the inner component of the object, remember:
 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" (dangling handles) occurring.
29. It is worthwhile to work for "exceptional safety" remember:
 The exception security function (Exception-safe functions) 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 assurance" 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.
30. A thorough understanding of the inside and outside of inlining please remember:
 Most inlining are limited to small, frequently called functions. This makes future debugging and binary upgrades easier, and minimizes potential code bloat issues, maximizing the chance of a program's speed increase.
 Do not declare them as inline just because the function templates appears in the header file.
31. Minimize compilation dependencies between files keep in mind that:
 The general idea of supporting "minimization of compilation dependencies" is that it depends on the declarative, not on the definition. The two instruments based on this conception are handles calsses and interface classes.
 The library header file should be in the form of "complete and declarative Only" (Full and Declaration-only forms). This practice applies whether or not the templates is involved.
6. Inheritance and object-oriented design 32. Make sure your public inheritance is molded out of the is-a relationship remember:
 "public inheritance" means is-a. Every thing that applies to base calsses must also apply to derived classes, because each derived class object is also a base class object.
33. Avoid concealing the inherited name remember:
The name within the derived classes will obscure the name within the base classes. No one has ever wished to do so under public inheritance.
 To let the masked name see the daylight, use a using declarative or transfer function (forwarding functions)
34. Differentiate between interface inheritance and implementation inheritance, remember:
 Interface inheritance differs from implementation inheritance. Under public inheritance, derived classes always inherits the interface of base class.
The pure virtual function specifies only interface inheritance.
 Simple (non-pure) impure virtual functions Specify interface inheritance and default implementation inheritance.
The non-virtual function specifies interface inheritance and mandatory implementation inheritance.
35. Consider alternatives other than the virtual function, remember that:
The alternative scheme of the virtual function includes many forms of nvi and strategy design patterns. The NVI technique itself is a special form of template method design mode.
 The disadvantage of moving functions from member functions to class external functions is that non-member functions cannot access the Non-public members of class.
The tr1::function object behaves like a generic function pointer. Such an object can accept all the callable objects (callable entities) that are compatible with the given target signature (target signature).
36. Never redefine the inherited non-virtual function, remember:
 never redefine the inherited non-virtual function.
37. Never redefine inherited default parameter values remember:
 never redefine an inherited default parameter value because the default parameter values are static bindings, and the virtual function--the only thing you should overwrite--is actually bound dynamically.
38. By compounding the mold out of the has-a or "according to the realization of something" please remember:
 Compound (composition) meaning and public inheritance are completely different
 in the application domain (application domains), compound means has-a (there is one). In the implementation domain (Implementation domains), compounding means is-implemented-in-terms-of (implemented according to something).
39. Using private inheritance wisely and prudently, remember:
private inheritance means is-implemented-in-terms of (according to something). It is usually lower than the compound level. However, this design is reasonable when derived class needs to access the members of the protected base class or need to redefine the inherited virtual functions.
 Unlike composite (composition), private inheritance can result in the optimization of empty base. This may be important for library developers who are committed to minimizing the size of objects.
40. Using multiple inheritance wisely and prudently, remember to:
 Multiple inheritance is more complex than single inheritance. It can lead to new differences and the need for virtual inheritance.
virtual inheritance increases the cost of size, speed, initialization (and assignment) complexity, and so on. If virtual base classes does not carry any data, it will be the most useful case.
 Multiple inheritance does have a legitimate purpose. One of the episodes involves the two-phase combination of "public inheriting a interface class" and "private inheriting a class of assistance implementations."
7. Template and generic programming 41. To understand implicit interfaces and compile-time polymorphism, remember:
Both classes and templates support interfaces (interfaces) and polymorphism (polymorphism).
 for classes, the interface is explicit (explicit), which is centered on the function signature. Polymorphism occurs at run time through the virtual function.
 for the template parameter, the interface is implicit (implicit) and is rooted in a valid expression. Polymorphism occurs at compile time through template-based and function-overloaded parsing (function overloading resolution).
42. Understand the double meaning of typename remember:
 The prefix keyword class and typename are interchangeable when declaring the template parameter.
 Use the Keyword typename to identify the nested subordinate type name, but not as the base class modifier in the base class lists (base column) or member initialization list (Member initial column).
43. Learn to handle names within a templated base class remember:
 the "this->" refers to the name of a member within the base class templates within the derived class templates, or through a clearly written "base class qualifier modifier".
44. Extract the parameter-independent code from templates remember:
templates generates multiple classes and functions, so any template code should not have a dependency on a template parameter that causes bloat.
 Code bloat due to non-type template parameters (Non-type templates parameters) can often be eliminated by replacing the template parameter with a function parameter or class member variable.
 Code bloat due to type parameter is often reduced by allowing specific types (instantiation types) with exactly the same binary representation (binary representations) to share the implementation code.
45. Use the member function template to accept all compatibility types, remember:
 Use member function templates (member function template) to generate "acceptable all compatible types" functions.
 If you declare member templates for "Generalization copy construction" or "generalization assignment operation", you still need to declare the normal copy constructor and copy assignment operator.
46. To define a non-member function for a template when a type conversion is required, remember:
 When we write a calss template, and the "related to this template" function supports "implicit type conversion of all parameters", define those functions as "friend functions inside the class template".
47. Please use the traits classes type information to remember:
traits classes makes "type-related information" available at compile time. They are accomplished with templates and "templates".
 Traits classes is likely to perform if...else tests on the type at compile time after consolidating heavy-load technology (overloading).
48. Recognize the template meta-programming please remember:
template metaprogramming (TMP, template metaprogramming) moves the work from the runtime to the compile time, because it enables early error detection and higher execution efficiency.
tmp can be used to generate custom code based on the policy choice combination (based on combinations of policies choices) or to avoid generating code that is not appropriate for some particular type.
8. Customize the new and delete49. To understand the behavior of New-handler, remember:
set_new_handler allows a client to specify a function that is called when the memory allocation is not met.
nothrow New is a fairly limited tool because it only applies to memory allocations, and subsequent constructor calls may throw exceptions.
50. Learn about the proper substitution of new and delete in practice remember:
 There are many reasons to write a custom new and delete, including improving performance, debugging the heap using errors, and collecting heap usage information.
51. Keep in mind when writing new and delete:
operation new should contain an infinite loop in which to attempt to allocate memory, and if it does not meet the memory requirements, call New-handler. It should also have the ability to handle 0bytes applications. The class-specific version should also handle "larger (error) applications than the correct size."
operation Delete should not do anything when a null pointer is received. The class-specific version should also handle "larger (error) applications than the correct size."
52. Write placement new also to write placement delete please remember:
 When you write a placement operator new, make sure that the corresponding placement operator delete is also written. If you do not do this, your program may have a memory leak that is hidden and is intermittent.
 When you declare placement new and placement Delete, make sure that you do not inadvertently (unintentionally) obscure their normal version.
9. Miscellaneous discussion 53. Do not neglect the compiler's warnings, remember:
 Take warning messages from the compiler seriously. Strive for "no warning" honors at the highest (most stringent) warning level of your compiler.
 do not rely on the compiler's alarm ability much, because different compilers do not have the same attitude towards things. Once ported to another compiler, the warning message you relied on might disappear.
54. Familiarize yourself with the standard library, including TR1, and remember that:
The main functions of c++ Standard library consist of STL, IOStreams and locales. and contains the C99 standard library.
TR1 adds support for smart pointers (such as tr1::shared_ptr), generalized function pointers (tr1::function), hash-based containers, regular expressions (regular expression), and 10 additional components.
TR1 itself is only a specification. To get the benefits of TR1, you need a physical one. A good source of physical resources is boost.
55. Make yourself familiar with boost remember:
boost is a community and a website. Dedicated to free, open source, peer review of C + + library development. Boost plays a powerful role in the C + + standardization process.
boost offers many TR1 component implementations, as well as many other library applications.

Effective C + + 55 and things to remember

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.