C ++ copy constructor and = assignment operator

Source: Internet
Author: User

First, make it clear:

The system has provided the default copy constructor and the = copy operator. That is, the so-called shallow copy.

But sometimes we have to provide our own rewrite. Generally, it is rewritten with pointers.

For a simple example, there is no pointer, so you don't have to rewrite it, just to demonstrate:

Class fraction {PRIVATE: int fenmu; // denominator int fenzi; // public: fraction (int x, int y) {fenzi = x; fenmu = y;} fraction () {} fraction (const fraction & fr); fraction & operator = (fraction & P); void display () {cout <fenmu <"" <fenzi ;}}; fraction: fraction (const fraction & fr) {cout <"test: Use copy" <Endl; fenmu = Fr. fenmu; fenzi = Fr. fenzi;} fraction & fraction: Operator = (fraction & fr) {If (this = & fr) return * This; fenmu = Fr. fenmu; fenzi = Fr. fenzi; cout <"test use =" <Endl; return * This;} int main () {Fraction F (1, 2); fraction F2 (f ); // use copy // f2.display (); fraction F3 = F2; // use copyfraction F4, F5; F5 = F4 = F3; // use = // f5.display (); return 0 ;}

Output:

test: use copytest: use copytest use =test use =

If a pointer exists, deep copy is required:

# Include <iostream> using namespace STD; Class ca {public: Ca (int B, char * CSTR) {A = B; STR = new char [B]; strcpy (STR, CSTR);} Ca (const ca & C) {A = C. a; STR = new char [a]; // If (STR! = 0) strcpy (STR, C. Str);} void show () {cout <STR <Endl ;}~ CA () {Delete STR;} PRIVATE: int A; char * STR;}; int main () {ca a (10, "Hello! "); Ca B = A; B. Show (); Return 0 ;}

Initializes an object by copying the status of another object of the same class.
Usage: when passed through a value, return through a value, or explicitly copy an object

Value assignment operator

What is returned: * this is generally returned through reference. That is to say, the assignment of the class defined by the user complies with the same conventions as that of the internal type. The assignment can also be used as an expression, that is, cascading.

There are no errors in the Self-assignment syntax, but if you do not implement the assignment operator well, the disaster may be waiting for you.
Therefore, you must ensure that the self-assignment is harmless, that is, you must add the self-assignment detection.

Cassignment & cassignment: Operator = (const cassignment & A) {If (this = & A) return * This ;//.... Assignment of work}

There are only two results for the value assignment operator: completely successful, the object is left intact, and an exception is thrown.

CAssignment& CAssignment::operator=(const CAssignment& a){    if( this == &a )        return *this;    CTemp* t = new CTemp;    //…..    delete _tmp;    _tmp = t;    return *this;}

The derived class uses the value assignment operator.

The value assignment operator in a derived class first calls its direct base class value assignment operator (assign values to the member objects declared in the base class ), then, call the value assignment operator of its member objects (change the Member objects declared in the derived class ). These assignments should usually appear in the same order as the base class and member object in the definition of this class.

CDerived& CDerived::operator=(const CDerived& r){CBase::operator=(r);_c = r._c;return *this;}

The correct format of the overload assignment operator is as follows:

The C ++ designer stroustrup has made a lot of effort to make the user's custom type as internal as much as possible.
Similar types of work. For this reason, he made a lot of efforts (such as heavy-duty operators, writing type conversion letters)
Number and copy constructor ). And you should continue.
Let's take a look at the value assignment. When the internal type is used, the value assignment operation can be chained like the following:
Int w, x, y, z; W = x = y = z = 0;
Therefore, you should also be able to link user-defined value assignment operations:
Cstring w, x, y, z; // MFC "Custom" Type
W = x = y = z = "hello ";
Because the combination of the assignment operators is inherently from right to left, the assignment above can be parsed:
W = (x = (y = (Z = "hello"); <=>
W. Operator = (X. Operator = (Y. Operator = (Z. Operator = ("hello "))));

This format indicates that the parameters w. Operator =, X. Operator = and Y. Operator = are the first
Operator = return value of the call. Therefore, the return value of operator = must be input.
The input parameter is accepted by the function itself. Generally, operator = the input should be a class object or
Class Object reference, in terms of efficiency, the latter is better than the former, so both input and return should
Is a reference to a class object.
And because there are
Int x, y, z; (x = y) = z;
Therefore, the following statement should be correct.
Cstring x, y, z; (x = y) = z;
The return value of operator = cannot be const (because the constant cannot be left)
Youyou
Cstring X; X = "hello"; <=>
Const cstring temp ("hello"); // generate a temporary object. Why is it const?
X = temp;
Therefore, to ensure that the preceding statement is true, the operator = input must be const.
So the best implementation is T & operator = (const T &);

Related Article

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.