复制构造函数和赋值运算符 [英] Copy constructor and assignment operator

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

问题描述

你好,我以为我做得对,但现在很困惑。假设我们有以下代码:

 MyClass object1; 
MyClass object2 = object1; // 我在这里想到复制构造函数而不是=运算符权限?

// 但是在这里,如果我有:
MyClass object3;
object3 = object1; // 在这种情况下,=运算符会被调用吗?





我有点困惑,因为在我的代码中我大多数地只有 MyClass object2 = object1; 调用类型仍然可以调用我的赋值(=)运算符。



有什么帮助吗?谢谢。

解决方案

如果要调用复制构造函数,请使用

 MyClass object2( object1); 



除此之外,在按值传递参数或按值返回时,将隐式调用复制构造函数。因此,函数

 MyClass myFunction(MyClass obj)
{
...
返回 x;
}



将隐式调用参数obj的复制构造函数并返回值x。但请注意,通过将函数修改为

 MyClass& myFunction(MyClass& obj)
{
...
return x;
}



将不会调用复制构造函数。在这些情况下,传递一个引用,这意味着内部只有一个指针被传入和传出。






如果对象不存在,将调用复制构造函数。否则,您的赋值运算符用于将值从一个对象复制到另一个已存在的对象。



在这两种情况下你的问题都会调用你的赋值运算符,因为你的对象已经存在。


ps。我已经检查过,似乎我泄漏了一个普通=运算符

的用法,这就是程序调用我的=运算符的原因。
否则,我在上面提到的我的初步答复似乎是真的。


Hi, I thought I had got it right but am confused now. Say we have following code:

MyClass object1;
MyClass object2 = object1; // I thought here Copy Constructor is called instead of = operator right??

// But here, if I have:
MyClass object3;
object3 = object1; // In this case = operator would be called right??



I am a bit confused because in my code I have mostly everywhere only MyClass object2 = object1; type of calls and still my assignment (=) operator gets called.

Any help? Thank you.

解决方案

If you want the copy constructor to be called, use

MyClass object2 (object1);


Other than that, the copy constructor is called implicitly when transfering arguments by value or returning by value. Hence, a function

MyClass myFunction (MyClass obj)
{
    ...
    return x;
}


would implicitly call the copy constructor for argument obj and for returning value x. Notice, however, that by modifying the function to

MyClass& myFunction (MyClass& obj)
{
    ...
    return x;
}


the copy constructor will not be called. In these cases a reference is passed, which means internally that just a pointer is being transferred in and out.


Hi,

Your copy constructor will be called, if the object does not exist. Otherwise your assignment operator is used to copy the values from one object to another already existing object.

In your question in both cases your assignment operator will be invoked because your object already exist.


ps. I''ve checked it seems I had leaked somewhere usage of a normal = operator
that is why the program was calling my = operator.
Otherwise, what I mentioned in my initial reply seem to be true.


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

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