C + + compiler is very smart! When you declare an empty class, the compiler will silently write some basic functions for you if your code is useful to this null class. So what are the functions that the compiler adds itself? Constructors , destructors , a copy constructor , and a copy assignment operator . Give an example to illustrate, if you write down:
Class empty{};
It's like you're writing a code like this:
Class Empty{public:empty () {...} Default constructor ~empty () {...} destructor Empty (const empty & RHS) {...} Copy constructor empty & operator= (const EMPTY & RHS) {...} Copy assignment operator/* data */};
However, it is important to note that:
only when these functions are called will they be created by the compiler .。
If you do not want to use the default constructor, you can manually create the constructor yourself, which will obscure the default constructor and no longer allow the default constructor to be called.
Both the copy constructor and the copy assignment operator are copy operations, and the copy operation copies the copy method of the base class for each parameter by invoking the parameters that need to be copied. Such as
Template<typename t>class nameobject{public:nameobject (const char * name, const t& value); Nameobject (const std::string & name, const t& value), ~nameobject (), ..../* Data */private:std::string namevalue; T ObjectValue;}; nameobject<int> No1 ("Test string", 2); Nameobject<int> No2 (No1);
At this point No2.namevalue takes no1.namevalue as the argument, Namevalue is a string type, so No2.namevalue will call the copy function of string to assign the value
No2.objectvalue is an int type that copies each bits of the no1.objectvalue directly to the assignment.
But not all cases the compiler can generate operator= methods, the situation is not satisfied mainly includes the following two kinds:
- The member variable to be assigned contains a reference
- A const variable is included in the member variable to be assigned
Smart you must have thought of it! By contrast, C + + does not allow reference to point to different objects. At the same time, assigning a const member to a value is a bad idea!
If you intend to support assignment operators within a class that contains reference members, you must define the copy assignment operator yourself.
Please remember:
The compiler can secretly create a default constructor for class, a copy constructor, a copy assignment operator, and a destructor.
[Effictive C + +] clause 05 Understanding what functions C + + silently writes and calls