Objective
For a class, the most basic three-class member functions are: constructors, destructors, and copy functions (copy constructors and = overloaded functions). Even if your class does not define these functions, C + + will automatically be created for you. This article will tell you about the three functions that C + + "secretly" created for you.
Knowing this, you can better understand how the code works, and thus write your own requirements (these three types) of functions, to ensure that the object efficient and economical.
The default constructors and destructors
The default constructor/destructor is primarily responsible for invoking the constructor/destructor of its base class.
Default copy constructor and = overloaded function
The default two functions simply assign a member of an object to a simple assignment.
This means that if the member of the class is a pointer type, then the pointers in the two objects will point to the same memory area when an assignment occurs between the two objects of the class. In this case, memory management can be complicated, and later articles will explain in detail how to solve the problem-sharing the memory area between different objects in the class.
Sometimes, if you do not need to implement sharing in memory, you can define these two functions yourself and assign new memory areas to the assigned objects.
So, what if a class member is a reference type? If the members of the object are simply duplicates, does a reference variable refer to the new variable? This is a violation of the C + + "Do not allow reference variables to target different objects" principle.
The answer is-C + + will refuse to compile the assignment of that line.
Summary
1. The work done by the compiler is equivalent to:
1 classEmpty {2 Public:3Empty () {}//default constructor4Empty (ConstEmpty &rhs) {}//Default copy constructor5~empty () {}//Default destructor6Empty &operator= (ConstEmpty &RHS);//default assignment operator overloading function7};
2. If C + + defaults to the three types of functions you have defined that are not your requirement, this is often the case, then you need to combine the actual situation, to customize the most suitable for their own function.
3. These three kinds of functions are very important, please make sure that they are correct, efficient, otherwise the memory leakage caused by the late project is very big.
Fourth: Understand the functions that C + + silently writes and calls