Effective 55 Terms for C + +

Source: Internet
Author: User
Tags traits

After reading effective C + + only feel the usual programming needs to pay attention to some of the problems, there is a certain harvest, but because there is no project practice,

Do not have a deep understanding of the situation, but also the follow-up practice ~

List 55 clauses:

1. Consider C + + as a language federation.

2. Replace # define with const, enum, inline as possible

A) for simple constants, it is best to replace a const object or an enum #define

b) for macros that resemble functions, it is best to replace the #define with the inline function instead

3. Use const whenever possible

A) declaring something as const can help the compiler detect incorrect usage. A const can be applied to objects within any scope, function arguments, function return types, member function ontologies.

b) The compiler enforces bitwise constness, but you should use "Conceptual constants" when you write programs

c) when the const and NON-CONST member functions have a substantially equivalent implementation, making the NON-CONST version call the const version avoids code duplication.

4. Confirm that the object was initialized before it was used

A) manual initialization of the built-in objects because C + + does not guarantee that they are initialized.

b) Constructors are best to use member initializers rather than using assignment operations within the constructor body. The initial Value column lists the member variables in the same order as they are declared in class. (Member variables first declare first initialized)

c) In order to exempt the "initialization Order of cross-compilation units" issue, replace the non-local static object with the local static object

5. Learn what functions are written and called by C + + by default.

A) The compiler can secretly create a default constructor for class, a copy constructor, a copy assignment operator, and a destructor.

6. If you do not want to use the compiler automatically generated functions, it should be explicitly rejected.

A) in order 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

7. Declare the virtual destructor for the polymorphic base class.

A) the base class for polymorphic (with polymorphic properties) should declare a virtual destructor. If class has any virtual functions, it should have a virtual destructor.

B) class is designed to not declare a virtual destructor if it is not used as a base class, or if it is not for polymorphic properties.

8. Do not let the exception escape the destructor.

A) destructors should never spit out exceptions. 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.

b) If the customer needs to react to an exception thrown during the operation of an action function, then class should provide a normal function (rather than a destructor) to perform the operation.

9. Never call the virtual function in the construction and destruction process.

A) do not call the virtual function during construction and destruction, because such calls never fall to the derived class (compared to the layer that currently executes constructors and destructors).

10. Make operator = return a reference to *this.

11. Process "Self-assignment" in operator =.

A) ensure that operator = 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.

b) Determine if any function operates on more than one object, and when multiple objects are the same object, its behavior is correct.

12. Do not forget each ingredient when copying objects.

A) The copying function should ensure that all member variables within the object and all base class components are copied.

b) Do not attempt to implement another copying function with one of the copying functions. The common function should be put into the third one and called by the two copying functions together.

13. Manage resources with objects.

A) to prevent resource leaks, use the Raii object, which obtains resources in the constructor and frees the resources in the destructor.

b) The two commonly used RAII class 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. Carefully copying behavior in the resource management class.

A) Copying the Raii object must replicate all the resources it manages, and the copying behavior of all resources determines the copying behavior of RAII redemption.

b) Common and common RAII class copying behavior is: Suppress copying, execute reference counting method. But other behaviors can also be achieved.

15. Provide access to the original resource in the resource management class.

A) APIs often require access to raw resources, so each RAII class should provide a means to "get the resources it manages".

b) access to the original resource may be transformed by a display or by an implicit conversion. Generally speaking, conversion is more secure, but it is convenient to convert customers implicitly.

16. Use new and delete in pairs to take the same form.

A) 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, be sure not to use [] in the corresponding delete.

17. Place the new Ed object into a smart pointer in a separate statement.

A) If you do not do this, once an exception is thrown, it is possible to cause an imperceptible resource leak.

18. Make the interface easy to use correctly, not easy to misuse.

A) good interfaces are easy to use correctly and are not easily misused. You should try to achieve these properties in your interface.

b) The "promote proper use" approach includes interface consistency and compatibility with built-in types of behavior.

c) The "Misuse of the Organization" approach includes the creation of new types, the restriction of types of operations, the binding of object values, and the elimination of customer resource management responsibilities.

d) Tr1::shared_ptr supports custom-made filters. This prevents DLL problems, which can be used to automatically unlock mutexes and so on.

19. The design class is like a design type.

20. Prefer to replace Pass-by-value with Pass-by-reference-to-const.

A) Please replace pass-by-value with Pass-by-reference-to-const as much as possible. The former is usually more efficient and avoids cutting problems.

b) The above rules do not apply to built-in types, as well as STL iterators and function objects. For them, Pass-by-value is more appropriate.

21. When you must return an object, don't be paranoid about returning to its reference.

A) 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 static object, you may need more than one of these objects. Clause 4 provides an instance of "reasonably returning reference in a single-threaded environment to a local static object".

22. Declare the member variable as private.

A) Remember to declare the member variable as private. This gives the customer access to data consistency, fine-grained access control, guaranteed constraints, and provides the class author with full flexibility.

b) Protected is not more encapsulated than public.

23. Rather non-menber, non-friend replace the member function.

A) rather than replace the Menber function with the Non-menber non-friend function. This can increase encapsulation, flexibility and scalability.

24. If all parameters require type conversion, use the Non-menber function for this purpose.

A) If you need a type conversion for all parameters of a function, including the metaphor parameter referred to by this pointer, then this function must be a non-menber.

25. Consider writing out a swap function that does not throw an exception.

A) when Std::swap is inefficient for your type, provide a Swap member function and determine that the function does not-throw an exception.

b) If you provide a menber swap, you should also provide a non-menber swap to invoke the former. For class (not template), also special Std::swap.

c) when calling swap, use the using declaration for Std::swap and then call swap without any namespace qualification adornments.

D) It is best to std::template the "User defined type", but never try to add something new to STD within STD.

26. Delay the time when the variable definition appears as much as possible.

A) This can increase the clarity of the program and improve the efficiency of the program.

27. Try to do less transformational action.

A) if possible, avoid transformation, especially in the efficiency-focused code to avoid dynamic_cast. If you have a design that requires transformational action, try to develop an alternative design that doesn't need to be transformed.

b) If the 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.

c) rather than using C++-style (new) transformation, do not use old-fashioned transformation. The former is very easy to identify, but also a comparative necromancy.

28. Avoid returning handles points to the inner component of the object.

A) avoid returning handles (including reference, pointers, iterators) to the inner object. Following this clause increases encapsulation, helping the const member function behave like a const, and will minimize the likelihood of a "virtual lift number card" occurring.

29. It is worthwhile to work for "exceptional safety".

A) The exception security function does not leak resources or allow any data structures to corrupt, even if an exception occurs. Such a function distinguishes three possible guarantees: the basic type, the strong type, does not throw the abnormal type.

b) "Strong assurances" can often be achieved with copy-and-swap, but "strong assurances" are not achievable or meaningful for all functions.

c) The "Exception security guarantee" provided by the function is usually the weakest of the "Exception security guarantee" for each function that it invokes.

30. Thoroughly understand the inside and outside of inlining.

A) limit the majority of inlining 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.

b) Do not declare them as inline just because the function template appears in the header file.

31. Minimize the compilation dependencies between files.

A) The general idea of supporting the minimization of compile dependencies is that it depends on the declarative, not on the definition. The two tools based on this concept are handle class and Interface class.

b) The library header file should be in "completely declarative" form. This approach applies regardless of whether the template is involved

32. Make sure your public inheritance is molded out of the is-a relationship.

A) "Public inheritance" means is-a. Everything that applies to base class must also apply to derived class, because each derived class object is also a base class.

33. Avoid concealing the inherited name.

A) the name within the Derived class will obscure the name within the base class. No one has ever wished to do so under public inheritance.

b) to let the masked name see the daylight, use a using declarative or referral function.

34. Differentiate between interface inheritance and implementation inheritance.

A) interface inheritance differs from implementation inheritance. Under public inheritance, derived class always inherits the interface of base class

b) The Pure class function specifies only interface inheritance.

c) Simple (non-pure) impure virtual functions Specify interface inheritance and default implementation inheritance.

d) The Non-virtual function specifies the interface inheritance and the mandatory implementation inheritance.

35. Consider alternatives other than the virtual function.

A) alternatives to the virtual function include NVi (Non-virtual interface) techniques and various forms of strategy design patterns. The NVI technique itself is a special form of template method design mode.

b) 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.

c) The behavior of the Tr1::function object is like a pointer to a general function. Such objects can accept all the tunable "compatible with a given target signature".

36. Never redefine the inherited non-virtual function.

37. Never redefine the inherited default parameter values.

A) because the default parameter values are static bindings, and the virtual function-the only thing you should overwrite----is dynamic binding.

38. By molding out has-a or "to achieve out of something"

A) The meaning of the compound and the public inheritance are completely different.

b) In the application domain, compounding means has-a. In implementing a domain, compounding means is-implemented-in-terms-of (implemented according to something).

39. Use private inheritance wisely and prudently.

A) private inheritance means is-implemented-in-terms-of. It is usually lower than the compound level. However, the design is reasonable when derived class needs to access the members of the protected base class or need to redefine the inherited virtual functions.

b) Unlike compounding, 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. Use multiple inheritance wisely and prudently.

A) Multiple inheritance is more complex than a single inheritance, which can lead to new ambiguity and the need for virtual inheritance.

b) Virtual inheritance increases the cost of size, speed, initialization (and assignment) complexity, and so on. If virtual base class does not carry any data, it will be the most useful case.

c) There is a legitimate use of multiple inheritance. One of the episodes involves a two-phase combination of "public inheriting a interface class" and "private inheriting a class of assistance implementations."

41. Learn about implicit interfaces and compile-time polymorphism.

A) Both class and template support interface and polymorphic

b) The interface is explicit for class, centered on the function signature. Polymorphism is through the virtual function method occurs in the run time.

c) for the template parameter, the interface is implicit and is rooted in a valid expression. Polymorphism is through template with the initialization and function overload resolution occurs at compile time.

42. Understand the dual meaning of TypeName.

A) When declaring the template parameter, the Prefix keyword class and typename are interchangeable

b) Use the Keyword typename to identify the nested subordinate type name, but not as the base class modifier in the base class list or Menber initialization list (member initial value).

43. Learn to handle names within a templated base class

A) within the derived class template, the "this->" refers to the member name within the base class template, or the "base class qualifier modifier" written out by a template.

44. Extract the parameter-independent code from the template

A) template generates multiple classes and functions, so any template code should not have a dependency on a template parameter that makes up the expansion.

b) Code bloat caused by non-type parameter template parameters can often be eliminated by replacing the template parameter with a function parameter or class member variable.

c) Code bloat due to type parameters can often be reduced by allowing the implemented type to share the implementation code with the exact same binary representation.

45. Use the member function template to accept all compatible types

A) Use the Menber function template to generate "acceptable all compatible types" functions.

b) If you declare menber template for "generalization copy construction" or "generalization assignment operation", you still need to declare the normal copy constructor and copy assignment operator.

46. Define a non-member function for a template when a type conversion is required

A) When we write a class template that provides the "related to this template" function to support "implicit type conversion of all parameters," define those functions as "friend functions inside the class template."

47. Please use the Traits class expression type information

A) Traits class makes "type-related information" available at compile time. They are implemented as template and template-specific.

b) with the consolidation of heavy-duty technology, traits class may perform if-else tests on the type at compile time.

48. Recognize template meta-programming

A) Template metaprogramming can move work from runtime to compile time, enabling early error detection and higher execution efficiency.

b) TMP can be used to generate custom code based on a combination of policy choices, or to avoid generating code that is not appropriate for certain special types.

49. Understanding the behavior of New-handler

A) Set_new_handler allows the client to specify a function that is called when the internal training allocation is not met.

b) Nothrow New is a fairly limited tool because it only applies to memory allocations, and subsequent constructor calls may throw exceptions.

50. Understand the appropriate replacement time for new and delete

A) 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. When writing new and delete, it is necessary to adhere to the general

A) Operator 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 have the ability to handle 0 bytes applications. The class-specific version should also handle "larger (error) applications than the correct size."

b) Operator Delete should not do anything when it collects null. The class-specific version should also handle "larger (error) applications than the correct size."

52. Wrote placement new also to write placement delete

A) When you write a placement operator new, make sure to also write the corresponding placement operator delete. If it is not covered, your program may be exposed to a memory leak that is slightly intermittent.

b) When you declare placement new and placement Delete, be sure not to inadvertently (unintentionally) obscure their normal version.

53. Do not ignore compiler warnings

A) Take a serious approach to the warning message issued by the compiler. Try to win the "no warning" honor under your compiler's highest warning level.

b) do not rely too much on the compiler's alarm capabilities, 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

A) The main functions of the C + + standard library are composed of stl,iostreams,locales. and contains the C99 standard library.

b) TR1 added smart pointers, generalized function pointers (tr1::function), hash-based containers, regular expressions, and additional 10 component support.

c) 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

A) boost is a community and a website. Dedicated to free, open source, peer review of C + + library development. Boost plays a powerful role in C + + standardization.

b) Boost offers many TR1 component implementations, as well as many other library applications.

Effective 55 Terms for C + +

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.