Outline and record of C + + programming specification (RPM)

Source: Internet
Author: User
Tags class definition compact version control system

This is a good book that allows you to recognize your mastery of C + +. What do I know about C + +, after reading it, and scoring for myself? The answer is less than 20 points. For me to take for granted the question, do not mention, remember some inspirational articles and details:

(* indicates not fully understood, after the strength of the upgrade to look back )

General questions:

1. Do not repeat code semantics in comments, which can easily create inconsistencies. You should write explanatory notes explaining the methods and principles.

2. Do not make mandatory formatting for each file in each project, in the same file style consistent.

3. The Hungarian notation is a mix of facilities in type unsafe languages, which can exist in object-oriented languages, but is not harmful and is not feasible in generic programming, and it is reasonable to disable the rules in the specification.

4. Replace the specified function single entry single exit with a function that advocates shorter and simpler functions.

5. "Defines a variable that has never been used" this warning can be eliminated by using it in a meaningless way. (If necessary)

6. "Missing return statement" can be added by adding an assert (! ") to the end of the function. Should never get here! "); Return-1 to remove the warning (!) String "result is false)

7. Using the Automated build system (automatic, reliable, single-action)

8. Using the version control system (CVS recommended, CVS is recommended for projects over 5 + years)

9. Invest in code review. (Prepare a check list)

A) Positive pressure

b) Improve quality

c) Exchange of ideas

D) rapid development of beginners

e) Form a team spirit

f) Enhance overall strength, enhance self-confidence, motivation and professional sense of honor

Design style (dependency management):

10. An entity should have only one compact responsibility (variables, classes, functions, namespaces, modules, and libraries), and as the entity becomes larger, its scope of responsibility expands, but it should not diverge.

11. Correct, simple and clear first: correct is better than speed. Simplicity is better than complexity. Clearer than ingenuity. Security is better than unsafe.

Avoid using the obscure attribute in the programming language. Should use the simplest and most effective techniques

12. Programming should know when and how to consider scalability

A) Use a flexible, dynamically allocated array

b) understand the actual complexity of the algorithm

c) Prioritize the use of linear algorithms or the fastest possible algorithms

D) Avoid algorithms that are inferior to linear complexity as much as possible

e) Never use an algorithm with exponential complexity

13. Do not perform immature optimizations: first of all, to keep the code clear and readable, easy to maintain, easy to refactor.

14. Do not make premature deterioration: Relax yourself and program easily. Don't be pessimistic about yourself without confidence.

A) You can use a reference pass but use a value to pass

b) using the + + prefix is good for the suffix

c) assigning values in constructors instead of using initialization lists

d) Use abstractions and libraries.

15. Minimize global and shared data: Avoid sharing data, especially global data. Sharing data increases coupling, which reduces maintainability and typically degrades performance. Fight for "no sharing", instead of data sharing by means of communication (such as Message Queuing).

16. Hide information: Do not expose the internal information of an abstract entity. Never set a data member of a class to public

17. Know when and how to do concurrent programming. (This part involves little, not much experience, looking back) if your application uses multiple threads or processes, you should know how to minimize shared objects and how to safely share objects that must be shared. The most important thing is to avoid deadlocks, live locks and vicious competition conditions.

18. Ensure that resources are owned by the object. Use explicit RAII (resource acquisition is initialized) and smart pointers.

19. Do not allocate more than one resource within the same statement.

20. Rather compile-time and connection-time errors, do not run-time errors (this article does not understand the discussion, no concept, look back again.)

* active use of const

22. Avoid using macros: in C + + you can use const or enum to define easy-to-understand constants, use inline to avoid the overhead of function calls, specify function series and type series with template, and avoid name collisions with namespace. (Omit a whole bunch of attack macros.) But # include #ifdef和assert仍不可避免.

23. Avoid using "magic number": replace them with symbolic names and expressions. Symbolic constants should be used instead of directly written dead strings, separating the strings from the code (all strings in a CPP file) so that non-programmers can also check and update them.

24. Important domain-specific constants can be placed at the namespace level.

25. Class-specific constants, you can define static integer constants in the class definition. (Declare constants in. h, define values in. cpp)

26. Declare variables as locally as possible. Because it is not reasonable to initialize variables is a common source of C and C + + errors. However, because constants do not add states, this article does not apply to constants.

27. Always Initialize variables: Uninitialized variables are common sources of errors in C and C + +. The habit of clearing up before using memory avoids this error and initializes it when the variable is defined.

28. Use default initial values or?: Reduce the mix of data flow and control flow.

29. Replace complex computational flows with functions.

30. Initialize the array, and the correct initialization does not really need to operate on all the data. For example: char path[max_path] = ['/0 '] creates an empty path filled with 0 (C-style string).

31. Avoid too long a function, avoid nesting too deep

A) as compact as possible, assigning only one duty to a function

b) Don't repeat yourself

c) Preferential use of && (relative to if nesting)

d) Do not use try too much

e) preferential use of standard algorithms

f) Do not branch (switch) based on the type tag, preferably using a polymorphic function

32. Avoid initialization dependencies across compilation units

33. Minimize the definition of dependency. Avoid cyclic dependencies.

A) dependency inversion principle: Do not allow high-level modules to rely on low-layer modules. Both should be made dependent on abstraction.

* The header file should be self-sufficient

35. Always write an internal # include protector, never write an external # include protector. (Hard to understand, exhausted, that is, the header file itself writes the protector, rather than the protection when it is included.) This avoids inconsistent protection names. There is no need to protect the character when it is included. )

36. Correct selection pass parameters by value, (SMART) pointer, or reference: distinguish input parameters, output parameters and input/output parameters, distinguish value parameters and reference parameters. The correct pass parameter.

37. For input-only parameters:

A) Always use const to restrict all pointers and references that point to only input parameters.

b) The object that takes precedence over values to get primitive types and lower copy cost values.

c) Prioritize the input of other user-defined types by a const reference.

d) If the function requires a copy of its arguments, you might consider passing the value by passing it instead of by reference. This is conceptually equivalent to passing a const reference pass plus one copy, which helps the compiler better optimize the temporary variables.

38. For output parameters or input/output parameters:

A) If the parameter is optional, or if the function needs to hold a copy of the pointer or manipulate the ownership of the parameter, it is preferred to pass (SMART) the pointer.

b) If the parameter is required, and the function does not need to hold a pointer to the parameter, or does not have to manipulate its ownership, then it should be passed by reference in precedence. This indicates that the parameter is required and the caller must provide a valid object.

39. Maintain the natural semantics of overloaded operators

* The standard form of operator and copy operator is preferred.

41. Preferential use of the standard form of + + and--. The prefix form is called first because it creates an object less. This is the mature optimization.

42. Consider overloading to avoid implicit type conversions. (You don't have to go through the hassle of creating temporary variables)

43. Avoid overloading &&, | | Or, (comma) (a lot of harm)

A) built-in &&| | Symbol is short-circuit operator, encountered false,&& will stop calculation, encounter true,| | will stop the calculation.

44. Do not write code that relies on the order of the function parameter evaluation: The order in which the function parameters are evaluated is indeterminate.

* * figure out what kind of class to write, and then write it according to the situation. Divided into: Value class base class traits policy class exception class.

46. Replace the giant class with a small class.

47. Replace inheritance with a combination: inheritance is second only to friend, which is the close coupling relationship in C + +. Tight coupling is a bad phenomenon and should be avoided as much as possible. (There's a lot of good behind it, but it doesn't mention the pattern.) )

48. Avoid inheriting from a class that is not designed to be a base class: To add a behavior, you should add a non-member function instead of a member function, and to add a state, you should use a combination instead of an inheritance. To avoid inheriting from a specific base class.

49. Preferential provision of abstract interfaces: Abstract interfaces help us to focus on the correctness of the abstraction and not be disturbed by implementation or state management details. Take precedence over the design hierarchy that implements the abstract interface (modeled abstract concept). DIP (Dependency inversioin Principle Dependency inversion principle) has three basic design benefits: stronger, more flexible, and better modular.

50. Public inheritance can be substituted. Inheritance is not for reuse, but for reuse.

51. When using inheritance, do not say "is a", and say "it behaves like a", this can avoid the description is easy to misunderstand.

* implement a security rewrite.

53. * Consider declaring a virtual function as non-public and declaring the public function non-virtual.

54. * To avoid providing an implicit conversion

55. * Set data members to private, no behavior aggregation (c-form struct)

56. * Do not disclose internal data

57. * Use Pimpl wisely

58. * Priority to write non-member non-friend functions

59. * Always provide new and delete together (this refers to overloading them one o'clock)

60. * All standard forms should be provided if the class-specific new is provided. (Normal, in-place and non-throwing)

61. Define and initialize member variables in the same order

62. Use initialization in the constructor instead of assignment.

63. Avoid calling virtual functions in constructors and destructors (* You can use the post constructor for similar purposes)

64. * Set the base class destructor to be public and virtual, or protected and non-virtual.

65. * Destructors, releases and interchanges must never fail.

66. Assignment and destruction in a consistent manner. If you define an assignment constructor, copy an assignment operator or any of the destructors, you may also need to define another or another two.

67. Explicitly enable or disable replication.

A) If the assignment does not make sense for your type, you can suppress the copy construction and copy assignment by declaring them as private, non-implemented functions.

b) If the copy and copy assignment is appropriate for the T object, but the correct copy behavior is different from the compiler-generated version, write the function yourself and set them to private.

c) Use the compiler-generated version, preferably with a clear comment.

68. * Avoid sectioning. Consider cloning instead of replication in the base class.

69. * Use the standard assignment form. When implementing operator=, you should use the standard form-a non-virtual form with a specific signature.

70. * Provide a swap that will not fail as long as it is possible (and provide it correctly)

71. Place the type and its non-member function interfaces in the same namespace.

72. * The types and functions should be placed in separate namespaces, unless they are intended to work together.

73. Do not write namespace using before the header file or # include

74. To avoid allocating and freeing memory in different modules

75. * Do not define entities with links in the header file

76. * Do not allow exceptions to propagate across module boundaries.

77. * Use a type with good portability in the interface of the module

78. * Rational combination of static polymorphism and dynamic polymorphism

79. The advantage of polymorphism is that the same piece of code can manipulate different types, even types that are not known when writing code.

80. * Intentional Explicit customization

81. * Do not special template functions

82. Do not unintentionally write code that is not generic

a) use! = instead of < to compare iterators

b) Use the iteration instead of the index access

c) use empty () instead of size () ==0

d) Use the highest-level classes in the hierarchy to provide the required functionality

e) write constant and correct code

83. Extensive use of assertions to record internal assumptions and invariant

84. Never write an expression with side-effects in an Assert statement

85. Establish a reasonable error handling strategy and strictly abide by it. Including

A) Identification: what is wrong

b) Severity: severity or urgency of each error

c) Check: Which code is responsible for checking for errors

d) Delivery: What mechanism is used to report and deliver error notifications in the module

e) Processing: Which code is responsible for handling errors

f) Report: How to log errors or notify users.

86. * Difference error and non-error

87. * Design and write error-Safe code

88. * Priority use Exception Report error

89. Throw by value, capture by reference

90. * Correct reporting, handling and conversion errors

91. * Avoid using exception specification

92. Vector is used by default. Otherwise, select a different suitable container

A) programming is correct, simple and clear is the first

b) When programming, consider efficiency only when necessary

c) write the transactional as much as possible. Strong error-Safe code

The following properties are provided in the. Vector:

A) guarantee the lowest space overhead in all containers

b) guarantee the fastest access to the stored elements in all containers

c) Ensure inherent reference locality, which means that adjacent objects in the container are guaranteed to be adjacent in memory, which is not guaranteed by other standard containers

D) ensure a C-compatible memory layout, which differs from other standard containers

e) guaranteed to have the most flexible iterator in all containers (random access iterator)

f) Almost certainly has the fastest iterator (pointer, or performance to but with the class, in non-debug mode the iterator class can often be compiled to have the same speed as the pointer), faster than any other container iterator.

94. Replacing arrays with vectors and strings

A) They can automatically manage memory

b) They have a rich interface

c) They are compatible with the C memory model

D) They are able to provide a larger range of inspections

e) They support these features without sacrificing too much efficiency

f) They help to optimize

95. * Exchange data using vectors (and string::c_str) and non-C++API

96. * Store only values and smart pointers in the container

97. * Use Push_back instead of other extension sequences

98. Multi-use range operation, less single element operation

99. * Real compressed capacity using accepted idioms, really delete elements

100. The algorithm is loop-just better. The algorithm is a cyclic "pattern" that adds a lot of semantic content and other rich content to the original loop implemented with only the for statement.

101. * Using the STL implementation with check

102. * Replace hand-written loops with algorithmic calls

A) improve the level of communication

b) correctness, good efficiency.

103. * Using the correct STL sorting algorithm

A) Partition, stable_partition and nth_element algorithms are linear in time.

b) Partial_sort, sort, stable_sort, and nth_element require random access iterators.

104. * Make predicates a pure function

A) The predicate is the function object that returns Yes or No. Mathematically, if the result of a function depends only on its parameters, the function is a pure function.

105. * Algorithm and comparator parameters should be used more function object less function

106. * Proper writing of function objects

107. Avoid using type branching, multi-modal

108. * Dependency type, not how it is represented

A) do not make any assumptions about the exact representation of the object in memory. Instead, let the type decide how to read and write its objects in memory.

109. Avoid using reinterpret_cast

110. Avoid using static_cast for pointers

A) replace it with dynamic_cast, refactoring, or even redesign.

111. Avoid Casting const

112. * Do not use C-style casts

113. Do not perform memcpy or memcmp operations on non-pod

114. * Do not use joint re-interpretation representations

115. Do not use variable length parameters (...)

116. Do not use invalid objects. Do not use unsafe functions

A) objects have been destroyed

b) Semantic Invalidation object

c) objects that have always been valid

117. * Do not handle arrays in a polymorphic manner

Outline and record of C + + programming specification (RPM)

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.