当从函数返回对象时,调用C ++中的复制构造函数? [英] Copy Constructor in C++ is called when object is returned from a function?

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

问题描述


  1. 在实例化一个对象并使用另一个对象的值初始化它时,我会理解副本构造函数。

  2. 按值传递对象时。

3。



我的问题是no.3
如果复制构造函数在一个对象的值被调用时



我的意思是拷贝构造函数是一个深拷贝的,并且引用一个对象作为参数

解决方案

它的调用是为了避免出现问题。作为结果的新对象从本地定义的对象初始化,然后本地定义的对象被销毁。



如果是深层复制用户定义的构造函数,一样。为将作为结果的对象分配第一个存储,然后调用复制构造函数。它使用传递的引用访问本地定义的对象,并复制新对象所需的内容。


I understand copy constructor is called on three instances

  1. When instantiating one object and initializing it with values from another object.
  2. When passing an object by value.

3. When an object is returned from a function by value.

I have question with no.3 if copy constructor is called when an object value is returned, shouldn't it create problems if object is declared locally in the function.

i mean the copy constructor is a deep copy one and takes reference of an object as parameter

解决方案

It's called exactly to avoid problems. A new object serving as result is initialized from the locally-defined object, then the locally defined object is destroyed.

In case of deep-copy user-defined constructor it's all the same. First storage is allocated for the object that will serve as result, then the copy constructor is called. It uses the passed reference to access the locally-defined object and copy what's necessary to the new object.

这篇关于当从函数返回对象时,调用C ++中的复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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