Advice on efficient C ++ Programming

Source: Internet
Author: User
Advice on efficient C ++ programming this is a summary of efficient C ++ programming, which is very helpful.
I. # differences between # include "filename. h" and # include <FILENAME. h># Include "filename. h" indicates that the compiler will start searching for this file from the current working directory. # include <FILENAME. h> indicates that the compiler will start searching for this file from the standard library directory.
Ii. Functions of header filesEnhanced security detection the library function can be conveniently called through header files without worrying about the implementation method.
3. *, & modifier locationInt * I, j; // better for read I = new int (0); j = 0; int * & Y = I; // pointer's reference for * and & modifiers, it is best to keep the modifier close to the variable name to avoid misunderstanding
IV. If statementDo not compare a Boolean variable with any value, which is prone to errors. Integer Variables must have values of the same type for comparison. Floating-point variables should be less than equal. You can compare them with null by comparing the difference with a smaller number, do not compare with Boolean and integer
V. Comparison of const and # defineConst has data types. # define does not have data types. In some compilers, const can be debugged, # define cannot be debugged. There are two ways to define constants in a class: 1. assign values to constants in the constructor initialization table while declaring constants without assigning values; (constants and reference type member variables must be initialized through the initialization list) 2. Use enumeration instead of const constants.
Vi. Method of transmitting the values of C ++ FunctionsThere are three methods: pass by value, pass by pointer, pass by reference void fun (char C) // pass by value void fun (char * Str) // pass by pointer void fun (char & Str) // pass by reference if the input parameter is passed as a value, it is best to use the reference transfer instead, because the reference transfer saves the construction of temporary objects and the return type of The Destructor cannot be omitted, even if there is no need to add a void
7. Pointers or reference constants in the function body cannot be returned.

Char * func (void) {char STR [] = "Hello word"; // This cannot be returned because STR is a specified variable and is not a common value, return STR will be canceled after the function is completed;
}

Pointer variables in a function are not automatically released as the function disappears.
8. Implementation Body of a memory copy Function

Void * memcpy (void * pvto, const void * pvfrom, size_t size)
{
Assert (pvto! = NULL) & (pvfrom! = NULL ));
Byte * pbto = (byte *) pvto; // prevents address change
Byte * pbfrom = (byte *) pvfrom;
While (size --> 0)
Pbto ++ = pbform ++;
Return pvto;
}

9. Memory Allocation MethodThere are three allocation methods. Please remember, maybe someone will ask you this question during the interview that day. 1. The static storage area has been allocated during program compilation, it exists throughout the running period, such as global variables and constants. (After the program is compiled, it runs in two parts: code and data. Data is allocated to the static storage zone, and the entire data is allocated to the entire data zone when the program starts running.) 2. stack allocation, the local variables in the function are allocated from this, but the allocated memory is easily Limited. 3. Heap allocation, also known as dynamic allocation. For example, we use new and malloc to allocate memory and delete and free to release memory.
10. Precautions for memory allocationWhen allocating memory with new or malloc, you must assign an initial value to this pointer. After you use delete or free to release the memory, you must point the pointer to null. You cannot modify the pointer data pointing to a constant.
11. Content replication and Comparison

// Array ...... Char A [] = "Hello word !"; Char B [10]; strcpy (B, A); If (strcmp (a, B) = 0) {}// pointer ...... Char A [] = "Hello word !"; Char * P; P = new char [strlen (A) + 1]; strcpy (P, A); If (strcmp (P, A) = 0 ){}

12. sizeof problemsRemember, C ++ cannot know the size of the object indicated by the pointer. the pointer size is always 4 bytes.

Char A [] = "Hello world !" Char * P = A; count <sizeof (a) <end; // 12 Bytes Count <sizeof (p) <Endl; // 4 bytes

In addition, in a function, the array parameter degrades to a pointer, so the following content is always output as 4

Void fun (char a [1000]) {count <sizeof (a) <Endl; // output 4 instead of 1000}

13. pointer1. the pointer must be initialized during creation. 2. The pointer must be set to null after free or delete. 3. The pointer length is 4 bytes. 4. When the memory is released, if the pointer is an array pointer, all memory must be released, such

Char * P = new char [100]; strcpy (P, "Hello World"); Delete [] P; // note that the preceding [] P = NULL;

5. The content of the array pointer cannot exceed the maximum ease of the array pointer. For example:

Char * P = new char [5]; strcpy (P, "Hello World"); // The error target is not large enough. Delete [] P; // note the previous [] P = NULL;

14. About malloc/free and new/deleteMalloc/free is the memory distributor of C/C +, and new/delete is the memory distributor of C ++. Note: malloc/free is a library function, while new/delete is the operator malloc/free. constructor and destructor cannot be executed, while new/delete can be new/delete and cannot be run on C, therefore, malloc/free cannot be eliminated. Both of them must be paired. In C ++, you can use the _ set_new_hander function to define how to handle memory allocation exceptions.
15. Features of C ++C ++ adds overload, inline, const, and virtual mechanisms to overload and inline: this can be used for global functions or member functions of the class; const and virtual: can be used only for member functions of the class. Overload: functions with the same name in the same class. The parameter determines which function to call. A function must have virtual keywords. A function with the same name as a global function is not called an overload. If you call a global function with the same name in a class, you must use the global reference symbol: reference. Override means that the function of a derived class overwrites the base class function: the function name is the same, the parameter is the same, the base class function must have the virtual keyword, And the range is different (the derived class and the base class ). Hiding means that the derived class shields the base class from functions with the same name. 1. The function names are the same, but the parameters are different. In this case, the base class function is hidden regardless of whether the base class has the virtual keyword. 2. If the function name is the same and the parameters are the same, but the base class does not have the virtual keyword (if any), the base class function will be hidden. Inline: The Inline keyword must be put together with the definition body, rather than just in the Declaration. Const: const is the abbreviation of constant, which means "constant. All things modified by const are protected by force, which can prevent unexpected changes and improve program robustness. 1. parameters are pointer-type parameters used for input. Adding const can prevent unexpected changes. 2. When the user type referenced by value is used as the input parameter, it is best to change the pass by value to reference and add the const keyword to improve efficiency. If the data type is internal, you do not need to do this. For example, change void func (A) to void func (const A & ). Void func (int A) does not need to be changed to void func (const Int & A); 3. Adding a const to a function whose return value is of the pointer type will make the function return value unmodifiable, the assigned variable can only be a const variable. For example, the const char * getstring (void) function and char * STR = getstring () function will cause an error. Const char * STR = getstring () is correct. 4. the const member function indicates that the function can only call the const member variable to improve the program's key robustness. For example, declare the int getcount (void) const function. In this function, only the const member variables can be called. Virtual: virtual function: a function that can be overwritten by a derived class. Pure virtual function: it is only an empty function and has no function implementation body;
16. What is the role of extern "C?Extern "C" is a specified symbol of a connection exchange provided by C ++. It is used to tell C ++ that this code is a C function. This is because after C ++ is compiled, the number of letters in the library will become very long, which is inconsistent with that generated by C. Therefore, C ++ cannot directly call the C function. After extren "C" is added, c ++ can directly call the C function. Extern "C" is mainly used to reference and export regular DLL Functions and when C ++ contains C functions or C header files. Add the extern "C" keyword before use.
17. constructor and destructorThe constructor of the derived class should call the constructor of the base class in the initialization table. The constructor of the derived class and the base class should add the virtual keyword. It is not easy to compile constructor and destructor.

# Include <iostream. h> class base {public:
Virtual ~ Base () {cout <"~ Base "<Endl ;}};
Class derived: public base {public: Virtual ~ Derived () {cout <"~ Derived "<Endl ;}};
Void main (void) {base * pb = new derived; // upcast Delete Pb ;}

Output result :~ Derived ~ Base
If the Destructor is not virtual, the output result is ~ Base
18. # ifndef/# define/# What is the role of endif?This header file is repeatedly referenced to the original address.

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.