Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:
复制构造函数和赋值运算符相似,因为它们都用于使用另一个对象初始化一个对象。但是,它们之间有一些基本的区别:
Copy constructor | Assignment operator |
---|---|
It is called when a new object is created from an existing object, as a copy of the existing object | This operator is called when an already initialized object is assigned a new value from another existing object. |
It creates a separate memory block for the new object. | It does not create a separate memory block or new memory space. |
It is an overloaded constructor. | It is a bitwise operator. |
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class. | A bitwise copy gets created, if the Assignment operator is not overloaded. |
Syntax: className(cont className &obj) {body} | Syntax: className obj1, obj2; obj2 = obj1; |
复制构造函数 | 赋值运算符 |
---|---|
当从现有对象创建新对象时调用它,作为现有对象的副本 | 当已经初始化的对象从另一个现有对象中分配了新值时,将调用此运算符。 |
它为新对象创建一个单独的内存块。 | 它不会创建单独的内存块或新的内存空间。 |
它是一个重载的构造函数。 | 它是一个位运算符。 |
如果类中没有定义复制构造函数,C++ 编译器会隐式提供复制构造函数。 | 如果赋值运算符未重载,则会创建按位副本。 |
句法: className(cont className &obj) {body} | 句法: className obj1, obj2; obj2 = obj1; |
Consider the following C++ program.
// CPP Program to demonstrate the use of copy constructor
// and assignment operator
#include <iostream>
#include <stdio.h>
using namespace std;
class Test {
public:
Test() {}
Test(const Test& t)
{
cout << "Copy constructor called " << endl;
}
Test& operator=(const Test& t)
{
cout << "Assignment operator called " << endl;
return *this;
}
};
// Driver code
int main()
{
Test t1, t2;
t2 = t1;
Test t3 = t1;
getchar();
return 0;
}
Output
Assignment operator called
Copy constructor called
Explanation: Here, t2 = t1; calls the assignment operator, same as t2.operator=(t1); and Test t3 = t1; calls the copy constructor, same as Test t3(t1);
解释:t2 = t1; 调用了赋值运算符,与t2.operator=(t1); 是相同的。Test t3 = t1; 调用了复制构造函数,与 Test t3(t1); 是相同的。