Suppose there is a myclass class as follows:
Class myclass {public: // constructor // copy constructor myclass (const myclass & that): int_data _ (that.int _ DATA _), dbl_data _ (that. dbl_data _), str_data _ (that. str_data _) {}// value assignment operator myclass & operator = (const myclass & that) {If (this! = That) {int_data _ = that.int _ DATA _; dbl_data _ = That. dbl_data _; str_data _ = That. str_data _;} return * This;} // some other methods: int int_data _; double dbl_data _; string str_data _; // when adding a new data member here, do not forget to add the corresponding code in the copy constructor and value assignment operations };
What are the problems with this class? The real problem is that the comment behind the private part points out the problem. Such operations are especially troublesome and prone to mistakes, as mentioned in the annotations. In fact, if we didn't write a copy constructor and a value assignment operator, C ++ will write a "default version" for us ".
The default version of the copy constructor is that all data members call the copy constructor (or a simple copy built-in type ), the default version of the value assignment operator calls the value assignment operator of each data member or simply copies the built-in type.
Therefore, for the above example, copying constructors and value assignment operators are completely unnecessary. Worse, they are the source of potential errors because they make the code vulnerable. If someone tries to change them, the Code may be broken.
Therefore, a better idea for the above example is to avoid writing copy constructors and value assignment operators.
Generally, there are several options:
- Default version automatically created by the compiler
- The copy constructor and the value assignment operator are declared private and are not implemented. Copying of any type is prohibited.
- Compile your own version
The third method should be avoided if possible. If you find that you have compiled a copy constructor or value assignment operator for a class, consider whether it is necessary. This approach may be avoided and converted to the first method (using the default version created by the compiler) or other methods (such as smart pointers ). If you are still unsure, you can use the second method. As long as there is no replication type, no error will occur. However, you need to pay attention to some usage of the class (for example, in vector <myclass>). You need to copy constructors and value assignment operators. Therefore, you must be cautious when prohibiting any type of replication, it must be understood that it limits certain options for class usage.
Summary:
- If possible, avoid writing copy constructors and value assignment operators.
- If the default version is not applicable, you can consider declaring the copy constructor and the value assignment operator as private, prohibiting the copying of class instances.
Copy constructors and value assignment operators