The difference between the assignment function and the copy construction

Source: Internet
Author: User

C + + copy constructor assignment constructor

=================================

In a word, the assignment function assumes that the object is defined, and that the copy construct is executed to create an object. A copy construct requires a deep copy.

Assignment Function General mode:

operator = (const type&  par) {  ///  (1) Check self-assignment if(    this = = &par  )     return * this;  //  (2) release the original memory resources  //(3) Allocate new memory resources, and copy the content, 2, 3 order is not pay attention to, the release is really the original memory can 
   
    //
    (4) Returns the reference to this object 
    return * this
    
    ; }    
   

Original address: http://blog.chinaunix.net/uid-25808509-id-354211.html

Similarities and differences of copy constructors and assignment constructors
Because not all objects use copy constructors and assignment functions, programmers may be somewhat dismissive of these two functions. Remember the following warnings before reading the text: If you do not actively write copy constructors and assignment functions, the compiler will automatically generate default functions in a "bit copy" manner. If the class contains pointer variables, then the two default functions imply an error. Take the example of two objects, A and B of the class string, assuming that the content of A.m_data is "Hello" and the content of B.m_data is "world". Assigning A to B now, the "bit copy" of the default assignment function means that b.m_data = A.m_data is executed. This will result in three errors: one is that B.m_data memory is not released, the memory leaks, and the b.m_data and A.m_data point to the same piece of memory, and a or B changes affect the other party, and the third is that the M_data is released two times when the object is being refactored. Copy constructors and assignment functions are very easy to confuse, often leading to error writing and wrong use. A copy constructor is called when an object is created, and an assignment function can only be called by an object that already exists. In the following program, the third statement is similar to the fourth statement, and you can clearly see which one called the copy constructor and which called the assignment function.
String A ("Hello");
String B ("World");
String C = A; //the copy constructor is called, preferably C (a);
c = b; An assignment function was called
   The third statement in this example has a poor style and should be rewritten as a string C (a) to distinguish it from the fourth statement.
Copy constructors and assignment functions for class string
Copy constructor
string::string (const String &other)
{
Allow operation of other private members m_data
int length = strlen (Other.m_data);
m_data = new Char[length+1];
strcpy (M_data, other.m_data);
}
Assignment function
String & string::operator = (const string &other)
{
(1) Check self-assigned value
if (this = = &other)
return *this;
(2) Releasing the original memory resources
delete [] m_data;
(3) Allocate new memory resources and copy content
int length = strlen (Other.m_data);
m_data = new Char[length+1];
strcpy (M_data, other.m_data);
(4) Returns a reference to this object
return *this;
}
The difference between a class string copy constructor and a normal constructor is that there is no need to compare null with a function entry because "reference" cannot be null, and "pointer" can be NULL. Class string assignment functions are much more complex than constructors and are implemented in four steps:
(1) The first step, check the self-assigned value. You might think that superfluous, someone would be stupid enough to write a = A, such as a self-assignment statement! Not really. But indirect self-assignment can still occur, for example
Content Self-assignment
b = A;
...
c = b;
...
A = C;
Address Self-assignment
b = &a;
...
A = *b;
Perhaps someone will say: "Even if there is self-assignment, I can ignore, a big deal of time to let the object copy themselves, anyway, no error!" "He's really wrong about that.. Look at the second delete, can you copy yourself after your suicide?? Therefore, if self-assignment is found, the function should be terminated immediately. Be careful not to check the self-assignment if statement
if (this = = &other)
Wrong writing becomes
if (*this = = other)
(2) Step two, Use Delete to release the original memory resource. If you don't release it now, you'll never get a chance, and it will cause a memory leak. "You can take a temporary variable, as long as you are sure to release the original memory."
(3) The third step is to allocate a new memory resource and copy the string. Note that the function strlen returns a valid string length that does not contain the Terminator ' \ S '. The function strcpy is copied together with '/'.
(4) The fourth step returns a reference to this object for the purpose of implementing a chain expression like a = B = c. Be careful not to write return *this as return. Can it be written as return? Is the effect not the same? No! Because we don't know the lifetime of the parameter other. It is possible that other is a temporary object that disappears immediately after the assignment, and return will be garbage.
Lazy way to deal with copy constructors and assignment functions
What if we really don't want to write copy constructors and assignment functions, and don't allow others to use the compiler-generated default functions?
   The lazy approach is to simply declare copy constructors and assignment functions as private functions without writing code.
For example:
Class A
{ ...
Private
A (const a &a); Private copy Constructors
A & operator = (const a &a); Private Assignment function
};
If someone tries to write the following procedure:
A B (a); A private copy constructor is called
b = A; A private assignment function is called
The compiler will indicate an error because the private function of a cannot be manipulated by the outside world.



One
copy construction, is an object to initialize one side of the memory area, this memory area is your new object's memory area assignment OperationFor an object that has already been initialized for operator= operation
Class A;
A;
A B=a; Copy constructor call
Or
A B (a); Copy constructor call
///////////////////////////////////
A;
A b;
b =a; Assignment operator invocation

You just have to remember that in the C + + language,
String S2 (S1);
String s3 = S1;
Only the grammatical form is different, the meaning is the same, both the definition and initialization, all call the copy constructor.

Two
In general, when a data member contains a pointer object, one of the two different processing requirements is to copy the pointer object, which is a reference pointer to the object copy, which in most cases is a copy, = is the Reference object's
Example:
Class A
{
int Nlen;
char * PDATA;
}
Obviously
A, B;
When A=b, there are two requirements for pdata data
Copy of the first
A.pdata = new char [Nlen];
memcpy (A.pdata, B.pdata, Nlen);
Another way (citation):
A.pdata = B.pdata

By contrast you can see that they are different
The first is often used with copy, and the second is implemented
You just have to remember that copy constructors are used for pointers in classes, copy between objects

Three
is not the same as the implementation of the copy constructor
The copy constructor is first a constructor that, when invoked, produces an object that is initialized by the object passed in by the parameter, which is the resulting object.
Operator= (); Is to assign an object to an original object, so if there is memory allocation in the original object to release the memory first, but also to check that two objects are not the same object, if you do not do anything.



It's also important to note thatthe copy constructor is a constructor and does not return a value

The assignment function needs to return a reference to the object itself so that the operation after the assignment

You must know this:

int A, B;

b = 7;

Func (a = b); Assign I to function func (int)

Similarly:

CMyClass obj1, Obj2;

Obj1. Initialize ();

FUNC2 (obj1 = obj2); If no reference is returned, the value cannot be passed to FUNC2.



Note:

CMyClass & CMyClass:: operator = (CMyClass & other)

{

if (this = = &other)

return *this;

Assignment operation ...

Return *this

}

==================================================================================

Both the assignment operator and the copy constructor use an existing B object to create another object, a. The difference is that the assignment operator handles two existing objects, that is, the pre-assignment B should be present; The copy constructor generates a completely new object, that is, a does not exist until the copy constructor is called.
   ctemp A (b);//copy constructor, C + + style initialization
ctemp a=b;//is still a copy constructor, but this style is only for C compatibility, as with the above effect, before which a does not exist, or is not yet constructed.
ctemp A;
a=b;//assignment operator
before that ,A has been constructed through the default constructor.
Example Summary:
Important: Classes that contain dynamically allocated members should provide a copy constructor and overload the "=" assignment operator.
Examples to be used in the following discussion:
Class Cexample
{
Public
Cexample () {pbuffer=null; nsize=0;}
~cexample () {delete pbuffer;}
void Init (int n) {pbuffer=new char[n]; nsize=n;}
Private
Char *pbuffer; The object in the class contains pointers to dynamically allocated memory resources
int nSize;
};
The main feature of this class is that it contains pointers to other resources.
Pbuffer points to a memory space allocated in the heap.
   First, copy constructor
Call copy Constructor 1
int main (int argc, char* argv[])
{
Cexample Theobjone;
Theobjone.init (40);
Now another object needs to be initialized to the state of the object one.
Cexample theobjtwo=theobjone;//Copy Constructor
...
}
Statement "Cexample Theobjtwo=theobjone;" Initialize the theobjtwo with Theobjone.
It is done in a memory copy and copies the values of all the members.
When finished, Theobjtwo.pbuffer==theobjone.pbuffer.
That is, they will point to the same place (the address space), although the pointer is copied, but the spatial content pointed to is not copied, but is shared by two objects. This does not meet the requirements, the object is not independent, and for the deletion of space to bring hidden trouble.
Therefore, the necessary means should be used to avoid such situations.
Review the following procedure for this statement: Create a new object Theobjtwo by copying the constructor (system default), and do not call Theobjtwo's constructor (Vs2005 tried).
You can add an output statement test to a custom copy constructor.
Attention:
For members that are allocated in free space, you should use deep copy instead of shallow copy.
Call copy Constructor 2
When the object is passed directly to the function as a parameter, the function creates a temporary copy of the object, which is also tuned to the copy constructor.
For example
BOOL testfunc (Cexample obj);
TestFunc (Theobjone); Object directly as a parameter.
BOOL testfunc (Cexample obj)
{
The operation for obj is actually done for a copy of the temporary copy
}
Call copy Constructor 3
When a local object in a function is returned to the function, a temporary copy of the local object is also created, and the copy constructor is called
CTest func ()
{
CTest Thetest;
Return thetest
}
   Second, the overload of the assignment character
The following code is similar to the previous example
int main (int argc, char* argv[])
{
Cexample Theobjone;
Theobjone.init (40);
Cexample Theobjthree;
Theobjthree.init (60);
An object assignment operation is now required, the original content of the assigned object is cleared, and the contents of the right object are populated.
Theobjthree=theobjone;
return 0;
}
also uses the "=" number, but unlike the example in "one," in the "one," example, "=" in the object declaration statement, which represents initialization. More often, this initialization can also be expressed in parentheses.
For example Cexample Theobjone (theobjtwo);
In this example, "=" indicates an assignment operation. Copy the contents of the object Theobjone to the object Theobjthree, which involves discarding the original content of the object Theobjthree, and copying the new content.
However, the default action of "=" simply copies the value of the member variable accordingly. The old value is naturally discarded.
Because a pointer is contained within an object, it can have undesirable consequences: to avoid a memory leak, a pointer member frees the space pointed to by the pointer to accept the new pointer value, which is determined by the characteristics of the assignment operator. But what happens if it is "x=x" that assigns itself to itself? X releases the memory allocated to itself, and then, when the value is copied from the memory pointing to the right of the assignment operator, the value is found to be missing.
Therefore, classes that contain dynamically allocated members should also consider overloading the "=" Assignment operation symbol in addition to the copy constructor.
The class definition becomes:
Class Cexample
{
...
Cexample (const cexample&); Copy constructor
cexample& operator = (const cexample&); Assignment overloading
...
};
Assignment operator overloading
Cexample & cexample::operator = (const cexample& rightsides)
{
Nsize=rightsides.nsize; Copy Regular members
Char *temp=new char[nsize]; Copy what the pointer points to
memcpy (temp, Rightsides.pbuffer, nsize*sizeof (char));
delete []pbuffer; Delete the original pointer to the content (leave the delete operation behind, avoiding the loss of the content in x=x special cases)
Pbuffer=temp; Establish a new point
Return *this
}
   the copy constructor uses the overloaded code of the assignment operator.
Cexample::cexample (const cexample& rightsides)
{
Pbuffer=null;
*this=rightsides//called "=" after overloading
}

The difference between the assignment function and the copy construction

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.