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

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

问题描述

当我们按值从方法返回对象时,为什么调用复制构造函数。请参阅下面的代码,因为我正在从方法中返回一个对象,同时返回控件正在击中复制构造函数,然后返回。我不了解以下内容:

1)为什么调用副本构造函数。

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

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

4)返回时复制对象内容的必要性是什么。

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天全站免登陆