Copy constructors and overloaded assignment operators in C + + summary _c language

Source: Internet
Author: User
Tags shallow copy volatile

Objective

This article summarizes the copy constructors and overloaded assignment operators in C + +, including the following:

1. Copy the constructor and the definition of the overloaded assignment operator;
2. The timing of the invocation of the copy constructor and the overloaded assignment operator;
3. Replication constructors and overloaded assignment operators to achieve the main points;
4. Copy some details of the constructor.

Definitions of copy constructors and overloaded assignment operators

As we all know, creating a class in C + + will certainly include constructors, destructors, copy constructors, and overloaded assignment operations, and even if you don't explicitly define it, the compiler will give you four functions. For example, the following classes:

Copy Code code as follows:

Class CTest
{
Public
CTest ();
~ctest ();

CTest (const CTest &);
void operator= (const ctest &);
};

For constructors and destructors that are not the focus of today's summary, today's focus is on copy constructors and overloaded assignment operations. The copy constructor prototype for the class is as follows:
Copy Code code as follows:

Class_name (const class_name &SRC);

In general, if we don't write a copy constructor, the compiler automatically creates a copy constructor (also called an implicit copy constructor) for each class; Conversely, if we write a copy constructor (an explicit copy constructor), then the compiler will not create it.

The prototype of the overloaded assignment operator for a class is as follows:

Copy Code code as follows:

void operator= (const class_name &);

Overloaded assignment operators are a special assignment operator that is typically used to assign an existing object to another object of the same type. It is a special member function, and if we do not define this member function, then the compiler will automatically produce this member function. The code generated by the compiler is the act of copying objects with a single member.

summed up the definition of copy constructors and overloaded assignment operators, just to let us know them without really delving into them. Next, take a closer look at the timing of their invocation. About their call time, I have not really understand, so here must be a good summary of the understanding.

Timing of invocation of copy constructors and overloaded assignment operators

Calls to copy constructors and overloaded assignment operators always occur inadvertently, and they are executed without our explicit invocation. There must be a lot of attention to this implicit invocation, which is usually a place of pitfalls. Now I'm going to use the actual example to verify the example as follows:

Copy Code code as follows:

#include <iostream>
using namespace Std;

Class CTest
{
Public
CTest () {}
~ctest () {}

CTest (const ctest &test)
{
cout<< "copy constructor." <<endl;
}

void operator= (const ctest &test)
{
cout<< "Operator=" <<endl;
}

void Test (CTest test)
{}

CTest Test2 ()
{
CTest A;
return A;
}

void Test3 (CTest &test)
{}

CTest &test4 ()
{
CTest *pa = new CTest;
return *PA;
}
};

int main ()
{
CTest obj;

CTest obj1 (obj); Calling the copy constructor

Obj1 = obj; Calling overloaded assignment operators

/* The copy constructor is called once in the process of the argument
* Obj1 the copy constructor is called to create a temporary object that has the same scope as the local variable in the function
*/
Obj. Test (OBJ1);

///The copy constructor is invoked when the value is returned, and the overloaded assignment operator is invoked when the return value is assigned to OBJ2
* When the function returns a value, a temporary object is also constructed; Call the copy constructor to copy the return value to the temporary object
*/
CTest Obj2;
Obj2 = obj. Test2 ();

Obj2. Test3 (obj); parameter is a reference, the copy constructor is not called

CTest Obj3;
Obj2. Test4 (); The return value is a reference and the copy constructor is not called

return 0;
}

Comments are added to the code, and there is no longer a detailed explanation. Again, if the object assigns another existing object to it at the same time it is declared, the copy constructor is invoked, and the overloaded assignment operator is invoked if the object already exists, and then another existing object is assigned to it. This rule is very applicable, I hope you can remember.

Key to implementation of replication constructors and overloaded assignment operators

In general, the compiler generates the default copy constructors and overloaded assignment operators for us, but in some special cases, we need to manually implement our own copy constructors.

As we all know, the default copy constructor and assignment operator are all "shallow copy," and simply copy the fields, so if the object contains dynamically allocated memory, we need to override the copy constructor or overload assignment operator ourselves to implement "deep copy". Ensure data integrity and security. This is what we often say about deep copies and shallow copies of the problem. Let me give you a simple example to illustrate:

Copy Code code as follows:

#include <iostream>
using namespace Std;

const int MAXSIZE = 260;

Class CTest
{
Public
CTest (wchar_t *pinitvalue)
{
Here, I malloc the memory
pvalue = new Wchar_t[maxsize];
memset (pvalue, 0, sizeof (wchar_t) * MAXSIZE);
wcscpy_s (Pvalue, MAXSIZE, Pinitvalue);
}

~ctest ()
{
if (pvalue)
{
Delete[] pvalue; Finalseabiscuit points out, thank you. 2014.7.24
Pvalue = NULL;
}
}

CTest (const ctest &test)
{
Malloc the new memory for the Pvalue
pvalue = new Wchar_t[maxsize];
memset (pvalue, 0, sizeof (wchar_t) * MAXSIZE);
wcscpy_s (Pvalue, MAXSIZE, Test.pvalue);
}

ctest& operator= (const ctest &test)
{
This is very important, please remember
if (this = = &test)
{
return *this;
}

Please delete the memory, this maybe cause the memory leak
if (pvalue)
{
Delete[] pvalue; Fanghenggang pointed out the problem. Thank you very much 2014.3.15
}

Malloc the new memory for the Pvalue
pvalue = new Wchar_t[maxsize];
memset (pvalue, 0, sizeof (wchar_t) * MAXSIZE);
wcscpy_s (Pvalue, MAXSIZE, Test.pvalue);
return *this;
}

void Print ()
{
wcout<<pvalue<<endl;
}

Private
wchar_t *pvalue; The pointer points the memory
};

int main ()
{
CTest obj (L "obj");
Obj. Print ();

CTest obj2 (L "obj2");
Obj2. Print ();
Obj2 = obj;
Obj2. Print ();

Obj2 = Obj2;
Obj2. Print ();

return 0;
}

In particular, it requires a lot of attention when implementing overloaded assignment constructors, in the code I also added a note, we can seriously read the code, and then understand, if you do not understand can leave a message to ask me, of course, if I understand the wrong, I hope you can give me, we make progress together.

Some details of the copy constructor

1. Which of the following are the copy constructors

Copy Code code as follows:

X::X (const x&);
X::x (X);
X::x (x&, int a=1);
X::x (x&, int a=1, int b=2);

These details are also mentioned here, I also read from other people's blog, here I also summed up. For a class X, if the first parameter of a constructor is one of the following:
Copy Code code as follows:

A) x&
b) Const x&
c) Volatile x&
d) Const volatile x&

And there are no other parameters or other parameters that have default values, then this function is a copy constructor.
Copy Code code as follows:

X::X (const x&); is a copy constructor
X::x (X&, int=1); is a copy constructor
X::x (x&, int a=1, int b=2); Copy constructors, of course.

2. More than one copy constructor can exist in a class

Copy Code code as follows:

Class X
{
Public
X (const x&); Copy Construction of const
X (x&); Non-const copy construction
};

Note that if there is only one copy constructor in a class that has a parameter of x&, then copy initialization cannot be carried out using either const x or volatile X objects. If a copy constructor is not defined in a class, the compiler automatically produces a default copy constructor. This default parameter may be either x::x (const x&) or x::x (x&), which is determined by the compiler according to the context. In my visual Studio 2012, when more than one copy constructor is defined, the compiler will have warning, but the program will run correctly.

Summarize

This article summarizes the copy constructors and overloaded assignment operators, the emphasis is on the timing of the invocation of the copy constructor and the overloaded assignment operator; for the deep copy and the shallow copy that everyone likes to summarize, I don't use too much text to explain, I think the above code is enough to explain the problem. In the end, the problem that I have been struggling with for a long time is summed up, and I understand it thoroughly.

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.