C ++ efficient programming

Source: Internet
Author: User

 

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 files
Strengthen Security Detection
The library function can be conveniently called through the header file without having to care about its implementation method.

3. *, & modifier location
Int * 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 them close to the variable name to avoid misunderstanding.

IV. If statement
Do not compare a Boolean variable with any value, which is prone to errors.
The integer variable must have the same type value for comparison.
It is recommended that floating point variables be less than equal, and the difference can be compared with a smaller number.
The pointer variable must be compared with null, not Boolean OR integer.

V. Comparison of const and # define
Const 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 without assigning values. (The values of constants and referenced member variables must be initialized through the initialization list)
2. Replace the const constant with enumeration.

Vi. Method of transmitting the values of C ++ Functions
There are three methods: pass by value, pass by pointer, and 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 and structure of the temporary object.
The return type of the function cannot be omitted, and a void must be added even if it does not exist.

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. After the function is completed, it will be canceled.
Return STR;
}

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 Method
There are three allocation methods. Remember, maybe someone will ask you this question during the interview that day.
1. The static storage area is allocated during program compilation and exists throughout the runtime, 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 area, and the entire data is allocated to the program when it starts to run)
2. For stack allocation, 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 allocation
When allocating memory with new or malloc, you must assign an initial value to this pointer.
After the memory is released with delete or free, the pointer must be directed to null.
The pointer data pointing to a constant cannot be modified.

11. Content replication and Comparison

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

12. sizeof problems
Remember, 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 =;
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 [2, 1000])
{
Count <sizeof (a) <Endl; // output 4 rather than 1000
}

13. pointer
1. 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 releasing the memory, if it is an array pointer, you must release all the memory, such

Char * P = new char [100];
Strcpy (P, "Hello World ");
Delete [] P; // note the previous []
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 big enough.
Delete [] P; // note the previous []
P = NULL;

14. About malloc/free and new/delete
Malloc/free is the memory distributor of C/C +, and new/delete is the memory distributor of C ++.
Note: malloc/free is a library function, and new/delete is an operator.
Malloc/free cannot execute constructor and destructor, while new/delete can
New/delete cannot run on C, so malloc/free cannot be eliminated
Both must be used in pairs.
In C ++, you can use the _ set_new_hander function to define how to handle memory allocation exceptions.

15. Features of C ++
C ++ has four new mechanisms: overload, inline, const, and virtual.
Overload and inline: can be used for global functions or member functions of the class;
Const and virtual: can be used only for class member functions;
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 Same Name functions of the base class.
1. functions with the same name but different parameters are hidden regardless of whether the base class has virtual keywords.
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, there is no 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 & );
3. Adding a const to a function with a return value of the pointer type will make the return value of the function unmodifiable, and the assigned variable can only be a const type 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 destructor
The constructor of the derived class should call the constructor of the base class in the initialization table;
The destructor of the derived class and the base class should contain 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.

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.