为什么当我们通过值从方法返回对象时,将调用复制构造函数 [英] why copy constructor is called when we return an object from a method by value

查看:179
本文介绍了为什么当我们通过值从方法返回对象时,将调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我们通过值从方法返回对象时,调用复制构造函数。请参见我的下面的代码,因为我从一个方法返回一个对象,而返回控件击中复制构造函数,然后返回。我不明白以下事情:

1)为什么它正在调用复制构造函数。

2)哪个对象隐式传递给复制构造函数,

3)对象复制构造函数将复制内容,

4)什么是在返回时复制对象内容的必要性。所以plz帮助。

why copy constructor is called when we return an object from a method by value. please see my below code in that i am returning an object from a method while returning control is hitting the copy constructor and then returning. i am not understood following things:
1) why it is calling copy constructor.
2)which object is passing implicitly to copy constructor,
3)to which object copy constructor will copy the content,
4)what is the necessity of copying the object content while returning. so plz help.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class ClassA
{
   int a, b;
     public:
   ClassA()
   {
     a = 10;
     b = 20;
   }
   ClassA(ClassA &obj)
   {
    cout << "copy constructor called" << endl;
   }
 };

 ClassA function (ClassA &str)
 {
  return str;
 }

 int main ()
 {
   ClassA str;
   function(str);
   //function(str);
   return 0;
 }


推荐答案

你调用的值不通过引用。因此,必须从当前对象实例化新对象,因为对象的所有成员在返回的实例中应具有相同的值。因为否则你将返回对象它自己,这将通过引用返回。在这种情况下,修改引用对象也会改变原始对象。这通常不是一个想要的价值返回时的行为。

The copy constructor is called because you call by value not by reference. Therefore a new object must be instantiated from your current object since all members of the object should have the same value in the returned instance. Because otherwise you would be returning the object it self, which would be returning by reference. In this case modifying the reference object would change the original as well. This is generally not a behavior one wants when returning by value.

这篇关于为什么当我们通过值从方法返回对象时,将调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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