Valid C ++ notes

Source: Internet
Author: User

Previous notes, posted, are more "personalized"

Introduction:
The main valuable part of this book is the design part. This part is only known to you !!

1. Do not fill in the number of books, and keep your energy 100% concentrated. You can also learn English when reading English!

2. Display constructor:
Class {
Explicit A (INT n = 0, bool B = true ){}
}
Void dosomething (A aobject );
Then:
A A1, A2 (28); fine
Dosomething (28); error! But dosomething (A (28); -- in this case, if excludes the "Explicit" declaring, then all right!
Constructors declare explicit are usually preferable to non-explicit ones to avoid intended behaviors.

3. Assignment and copy constructor. (what is post call = when the operator calls the copy constructor)
A A = B; this callthe copy constructor.
But:
A;
A = B; this is a asignment.
Dosomething (a); in this case, the compiler will create a temp object which use a copy constructor on 'A '.

4. undefined behavior.
Which is normally caused by Invalid pointers. (So if find the program, sometime runnnings normally, other times crashing, check the pointers first !)

5. Establish the client concept. How to Create a friendly interface to your client (the ones who will depend on your codes)

6. multi-threaded programming. This is an important point. It's okay to study it in depth. Especially in the embedded field.

7. c ++ many concepts and design patterns should be based on examples. Through examples to deepen understanding. Therefore, when reading Objective C ++, the simple items do not have much guiding significance. The key is to deepen understanding through practice.

========================================================== ======================================
The following official start
========================================================== ======================================
1. Regard C ++ as a combination of languages:
C;
Class C ++;
Template;
STL;
Four major blocks ~~

2. Leave more things to the compiler rather than the pre-processor!
The target file will contain a symbol table. If # define is used, the macro name will not appear in the symbol table.
Constant pointer: the content of a region is fixed, and we direct the pointer to it. Without a doubt, we must define the const T * const Pt = ** method (const is always the stuff on its right ).
Class member constant: because it is a constant, only one copy is required, so it should be defined as static.
Enumeration: The Enumeration type is int type, so when int type constants are used, enumeration is a good choice.
Macro function hazard: When you pass in an expression, such as a ++, the situation is hard to predict. Regardless of the semantics, macros are rather ugly. Use inline to replace macros and help with templates. For example:
Template <class T> inline T & MAX (T & A, T & B) {return A> B? A: B;} is referenced ~~

3. Use const everywhere.
If the word const appears to the left of the asterisk, What's pointed to is constant; if the word const appears to the right of the asterisk, the pointer itself is constant;
Iterator can be interpreted as T * in terms of semantics. Therefore, if the pointer is a constant, it should be affirmed by iterator const (equivalent to const iterator. If the object to be pointed to is a constant, using const_iterator.
That is, const iterator is a constant pointer. Const_iterator points to constants.
It is more efficient to pass parameters through constant reference: first, it must be declared as a constant, because the original object cannot be changed, and second, it must be declared as a reference, so as to avoid calling the copy constructor.

4. Always remember to initialize an object (including built-in objects ).
Manually initialize objects of built-in type, because C ++ only sometimes initializes them itself.
In a constructor, prefer use of the member initialization list to assignment inside the body of the constructor. List data members in the initialization list in the same order they're declared in the class.
Avoid initialization order problems loss SS translation units by replacing non-local static objects with local static objects.

5. Try to use <iostream> instead of <stdio. h> or <iostream. h> (the name of <iostream. h> appears in the global space)
Try to use new and delete instead of malloc and free. Malloc and free are just simple memory allocation and memory release.
Suggestion: use new and delete with one mind.

6. Try to use C ++-style annotations, that is //
In my opinion, the key is to build your own style.

7. Ensure that all new memory is released. Do not forget to release the class pointer member in the destructor. The easiest example is:
String * pstr = new string [100];
Delete pstr; // No no, just release one string block exception occurs in vc6.0
Delete [] pstr; // OK
Principle: If you use [] in new, do not forget [] During structure analysis.
Typedef string commandlines [4]; // from now on commandlines = string [4] -- the best way is not to do this silly thing.
Commandlines lines; Delete [] lines.

8. There should be a sense of guilt in writing programs without exception handling. You have left a hidden danger, so you cannot say that it is the same day.
Is memory allocation always successful? The new macro can be defined in C ++:
# Define new (PTR, type )/
Try {PTR = new type ;}/
Catch (STD: bad_alloc &) {assert (1 );}
But this is not a good method!
A good method is:
Call the set_new_handler function. Header file <New>: this can be processed in the release version.
-- There is a lot of content in this section, so you have time to read it carefully!

9. How to write new and delete functions ~~ (When used)
Why write? For efficiency (so we usually don't need it)

10. If the class has a member variable, remember to write a copy constructor and A = Operator. Because you do not do this, the compiler will have a default copy when it encounters a = B. As a result, the pointer members of the two classes point to the same memory, which is inconsistent with our requirements.

11. Use the initialization parameter list or the init private initialization function to avoid completing the initialization in the constructor.
The initialization sequence of the members is the same as that of the Declaration. It is irrelevant to the initialization parameter list sequence.
The const member must be initialized in the parameterization list.

12. Use static variables to record the number of class objects and use static variables to implement the sington mode. Remember to declare the destructor of the base class as virtual. Otherwise, it is unpredictable to delete the derived class object with the base class pointer.

13. Consider a problem that has not been considered:
Why can assign operators be connected? A = B = c = D = 0
How is the compiler analyzed? A = (B = (C = (D = 0 ))
Analysis D = 0, = Operator function input parameter 0 (actually there is also this pointer) and return a reference as the previous = parameter
-- Let = function return * This. Check your assignment !!

14. classes that contain referenced members and const members must implement the copy and = operators themselves. Otherwise, the compiler rejects automatic copy or assignment.

15. The interpreted language is easier to perform runtime checks, but C ++ is not. Therefore, leave errors to the compilation connection period as much as possible. Once the program runs, there will be no more unexpected errors. Therefore, C ++ programmers must be proficient and have a deep understanding of the compiler.

16. Let's consider the following situation:
The construction of a depends on the construction of a static object of B, and the construction of B depends on the construction of a static object of. What should I do?
There is no doubt that this static link should be transferred out of the constructor, that is, the B member should be removed from Class. Move it to the function.
See the following code:
B & A: getb ()
{
Static B;
Return B;
}
When to initialize B? The first time you enter this function. B will also be defined in the global space, with only one copy. Solve the problem!
This is the singleton mode. Of course, the best way for Singleton is to provide a static Singleton function.

17. Pay attention to compilation warnings. When writing high-quality code, locate the warning level at the highest level (you can manually turn it off) and clear all warnings.
-- In principle, it is okay to ignore a warning, but you must clear the meaning of this warning.

18. There are still some tests to verify the namespace.

19. Everything in the C ++ standard library is a template. For example, cout is the object of ostream and ostream is the definition of typedef basic_ostream <char> ostream. Another example:
Template <class chart, class traits = char_traits <chart>, class Allocator <chart> class basic_string;
Typedef basic_string <char> string;
-- Use standard libraries and containers and Algorithms for efficiency and security.

20. Why should we emphasize fast development? Because the most important part in software development is to implement software functions that are different from those of your competitors.

21. To understand C ++, first understand the objective of C ++, so you can read Benjamin's book. See what the designer says.
C ++ is only 6 blocks:
C. overload, object-oriented, template, exception, and namespace.
-- General objective of C ++:
It is compatible with C and has the same efficiency as C (within 5%). It is not a teaching language but a language that solves practical problems.
Many problems are based on the above considerations (see what meyes says)

22. c ++ Derived classes hide functions of the same name of the parent class by name (not by function prototype. For example:
If the base class void F (int I); derived class void F (double D); then they do not constitute an overload relationship, but the latter overrides the previous one (unless the using statement is used ).

23. Strive to make the class Interface complete and minimal. Do not combat user enthusiasm for using them. This is easy to use and can be used to achieve our goals.

24. differentiate between member functions, non-member functions, and friend functions. Do not think this is very simple. It is really difficult to make a perfect and correct judgment. We suggest reading the example given by reading a book.
Exercise caution when using youyuan. In many cases, it is enough to declare that the public inline can be replaced by member functions, so there is no performance loss.

25. Avoid data members in the public interface. In this way, you don't need to think about whether to use parentheses for this member. The function is used to access members in a unified manner.
Meyes: How many times do you need to grasp your head in your life.
-- Of course, there are other advantages. Such an interface is more flexible. Because it is a function, our class can be modified without the client having to modify their code.

26. When an object must be returned, do not try to return a reference (think about the essence of the reference as an alias, there must be an object already created ).
There is a saying in C ++ that it is best to make the program efficient, but not too efficient.
The purpose of reference is to avoid calling Constructor (constructor is often recursive and overhead is very good ).

27. Do not make too many overloaded functions. Think about whether the number of overloaded functions can be reduced by default parameters. But do not be absolute. Seeking truth from facts!

28. avoid overloading the pointer type and number type. Disable the compiler to automatically generate certain functions: declarative but not implemented.

29. global namespace Division: In a large project, this is required (? Haha ). If it is a big project, we suggest you study it carefully.

30. Why is design the key, and encoding not the key? For large system projects, interfaces tend to be stable before implementation of classes.
C ++ is a highly typed language. As long as appropriate classes, templates, and function declarations are designed, the specific implementation of the Code is not difficult. There are some classes (classes that are frequently used in the entire project, just like simple classes, should be abstracted and defined first ).

31. The objects declared by const are not necessarily Const. It's just like someone you love says they love you forever, but it's not safe. Simplest:
Const B; char * STR = * B ;...
Whether the content of B is always the same depends on whether B's design is smooth.
-- In some cases, returning a const pointer is a good idea. Keep the replication work out. (You can use the data you love, but don't fix it)

32. Avoid such a member function: the returned value is a non-const reference or pointer to the member, but the access level of the member is lower than that of the function (this is called Backdoor ).

33. Do not return the pointer of a local variable or the reference of a new object.

34. Try to postpone variable definition. For the following reasons:
1. The definition needs to call the constructor, with overhead. Some variables only appear in some branches and should not be constructed at the beginning.
2. Increase program readability

35. Purpose of inline: To generate shorter code (think about function calling as code overhead), Faster execution efficiency (based on more code and higher cach hit rate ).
-- The Inline and register keywords are both recommended. (Most compilers reject inline functions that are more complex, so you can find out them in the disassembly language vc6.0 ).
Don't be superstitious about inline. It is mainly used for get and set members and simple computation (such as returning a computing result). In some cases, you may wish to use macros instead of killing this guy with a single stick.

36. Minimize the compilation dependency between files. The purpose of this operation is to quickly recompile the connection after modifying a file.
-- C ++ does not do well in separating interfaces from implementations (users who use interfaces never need to know how interfaces are implemented ).
The solution is to replace "dependency on class definitions" with "dependency on class declarations ".

37. Continue the previous topic and merge it:
Try to prevent header files from relying on other files (except standard library files). If not, use the class declaration instead of class definition.
Specifically: If you can use the object pointer or reference, do not use the object itself (defining the reference and pointer of an object only involves the object Declaration-why? Because objects need to be allocated space, you need to know the size of the space and the details of the object, but the pointer and application are both 4 bytes, just let the compiler know that this class name is valid)
Another point is that when declaring a function, if a class is used, the definition of this class is absolutely not required, even if the parameter and return value are passed by passing the value. -- Unexpected.

38. I would like to talk about the above. That is, the role of the header file (the CPP file will be inserted during the compilation period and then compiled for a single CPP file). The header file is the role of the first statement, and the second is the definition of some constants, third, public part extraction (such as the inline function ). It can be seen that we often use the # include header file. In fact, many of the header files introduced are irrelevant to the CPP compilation. A header file may be introduced for a declaration. In fact, we can declare it on our own without referencing the header file (provided that the preliminary design is sufficient)

39. Let's take a look at the terms below:
Handle class, envelope class, subject class, new class, and Protocol class.
-- Please read the book carefully without making a table (the discussion on the Internet may be more valuable ). In short, the problems reflected in this topic are indeed not small issues, and some compiler knowledge is also related to the design pattern.

40. Public inheritance represents a "yes" relationship. Remember, this is not a knowledge point, but a design principle. The B Public inherits from a, so a Includes B in concept, rather than B contains. B can be used wherever a is used. Otherwise, B cannot be used.
-- Public inheritance <=> is

41. differentiate between interface inheritance and implementation inheritance.
A tip: declare the protected member function and public virtual function. Protected functions are functional entities, while public functions are external interfaces. In this way, the derived class can choose whether to implement the implementation provided by the parent class. If you want to call the protected function of the parent class, do not rewrite the Public Virtual Interface by yourself. This section is actually very good ~~.

42. Related to the above topic: Do not redefine the inherited non-virtual functions. You will ask: is it so serious? To avoid confusion, do not do this.

43. Never redefine the inherited default parameter values (mainly refers to the redefinition of virtual functions ). The reason is that virtual functions are dynamically bound, but default parameters are statically bound. If you design a compiler, you will do the same. For a * pA = new B () Code, the compiler can only (currently) Understand Pa as a pointer to Class.

44. Don't be lucky to use the "downward conversion" of the class hierarchy "!

45. Three relationships. {// The beyes example shows how to use the list template to implement the set template. Obviously, this is an has-a relationship.
Is-,
Has-,
Use-
} Two usage methods {
Composition, combination
Aggregation, aggregation
}

46. differentiate inheritance from template. If the type affects behavior, use inheritance and polymorphism. Otherwise, use the template.

47. Speaking what you want to say is only half of the success. It is equally important to understand what you say. Implementation is the last step.

 

 

 

 

 

 

 

 

 

 

 

 

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.