C++拷贝构造函数和赋值运算符根本的不同

xiaoxiao2021-02-28  122

首先要说明的是,若用户没有定义,C++隐式声明一个拷贝构造函数和一个赋值运算符(完成按数据成员复制的动作)。二者很像,但是在下边这点上有很大的不同:拷贝构造函数是只在对象实例化时才会被调用,也就是说,在拷贝构造函数调用期间,这个对象处于一个未决状态(直到拷贝构造函数被成功调用),另外拷贝构造函数不返回任何值,void都没有。而赋值运算符则在一个现存的对象被赋予新的值时被调用,并且它有返回值。

在下边这个例子中我们能看到并不是出现“=”就是调用赋值构造函数:

#include using namespace std; class Test { public: Test() { ctor_count++; cout<<"ctor "< } Test(const Test & r) { ctor_count++; cout<<"copy ctor "< } Test & operator= (const Test& r) { ctor_count++; cout<<"assignment op "< return *this; } private: static int ctor_count; //only a declaration }; int Test::ctor_count=0; // definition + initialization int main() { Test test; Test test1=test; Test test2(test); Test test3=test2=test1; return 0; }

运行结果为

[root@localhost ~]# ./a.out ctor 1 copy ctor 2 copy ctor 3 assignment op 4 copy ctor 5

我们看到实例化test对象时调用了默认构造函数,test1使用了拷贝构造函数(因为这是一个新的对象产生),test2时也是用了拷贝构造函数,而test2=test1则使用了赋值构造函数(没有新的对象产生),test3=test2则使用了拷贝构造函数,原因同上。

 

所以要看是不是有新的对象产生,才能决定到底是调用了拷贝构造函数,还是赋值运算符。

转载请注明原文地址: https://www.6miu.com/read-29059.html

最新回复(0)