复制构造函数和赋值运算符之间的区别 [英] difference between copy constructor and assignment operator

查看:101
本文介绍了复制构造函数和赋值运算符之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了[问题](有什么区别和赋值运算符之间的区别?),并理解了复制构造函数和赋值运算符之间的区别.现在我的问题是尽管复制构造函数会初始化先前未初始化的对象,而赋值运算符将替换先前初始化的对象中的数据,最终结果有何不同?我认为两种情况下的最终结果都是正确的吗?最后,通过(CC)复制后,我们得到相同的输出,即使使用(AO)之后,我们也得到相同的输出.我在这里有意义吗?有人可以澄清一下在实际应用中有什么区别吗?

I have gone through [question] (What's the difference between assignment operator and copy constructor?) and understood difference between a copy constructor and assignment operator. Now my question is although copy constructor initializes the previously uninitialized object where as assignment operator replaces data from previously initialized object what's the difference in terms of final outcome. I am thinking that final outcome in both case comes out to be same right? In the end after copying via (CC) we get the same output and even after using (AO) we get the same output. Am I making sense here? Can someone please clarify what is the difference in terms of real world application?

推荐答案

除了您所说的以外,没有什么区别.
CC适用于新的统一对象(毕竟是构造函数),而运算符适用于现有对象.
可以用普通的构造函数然后使用赋值op(在通常的类中)代替CC的用法,但这将不如直接使用复制数据进行构造有效.
例如

Other than what you said, there is no difference.
The CC works on new unitizialied objects (it´s a constructor after all), the operator on existing ones.
The use of the CC could be replaced with the normal constructor and then the assignment op (in usual classes), but this would be not as efficient as the direct construction with copied data.
Eg.

class C
{
private:
    vector<int> v;
public
    C()
    {
        //fill v with 10^9 slowly generated random numbers, takes ca. 2 days
    }
    C(const C& c)  //could be auto-generated in this case
    {
        v = c.v;
    }
    C &operator=(const C& c)  //could be auto-generated in this case
    {
        v = c.v;
        return *this;
    }
};

...

C oldc;

...

//either
C newc(oldc);
//or
C newc; //takes 2 days
newc = oldc;

另一个原因,某些非平凡的类没有(公共)默认构造函数,并且只能通过从某个位置复制现有对象来创建.

Another reason, some nontrivial classes have no (public) default constructor and can only be created by copying existing objects from somewhere.

这篇关于复制构造函数和赋值运算符之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆