Today, my colleague encountered a question about copying constructors.CodeIt is roughly as follows:
Class test {public: Test (size_t size) {v. Assign (size, 1) ;}test (const Test & RHs) {v = RHS. V ;}~ Test () {} PRIVATE: vector <int> V ;}; class another {public: Another (): V (7) {} another (const another & RHs) {v = RHS. V ;}~ Another () {} private: Test V ;};
At first glance, it seems that there is no problem, but GCC cannot be compiled. The following error is reported:
In the code above, the test class already has constructor and copy constructor. Why must I provide a default constructor for GCC? This issue involves the initialization list in the C ++ constructor.
When writing constructor, many people will mean to use the initialization list to avoid resource loss of multiple constructor. However, when writing a copy constructor, this is what we write most of the time.
Class test {public: Test (): A (0) {...} test (const Test & RS) {A = Rs. ;...}~ Test () {} PRIVATE: int ;};
This is the crux of the problem. For a class, the member variable only declares a variable, and the real definition is done in the constructor. Therefore, if you are in the constructor (including the copy constructor, if the member variables are not initialized in the initialization list, the process is equivalent to calling the default constructor to initialize the member variables first, just like the method of copying the constructor in the code above, then call the = operation to assign values to the member variables. As a result, the above GCC requires the provision of Default constructors.
To solve this problem, we changed the code to the following by using the initialization list, and the problem disappeared.
Class test {public: Test (size_t size) {v. Assign (size, 1) ;}test (const Test & RHs): V (RHS. v ){}~ Test () {} PRIVATE: vector <int> V ;}; class another {public: Another (): V (7) {} another (const another & RHs ): V (RHS. v ){}~ Another () {} private: Test V ;};