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

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

问题描述

我知道在三个实例上调用了复制构造函数

I understand copy constructor is called on three instances

  1. 实例化一个对象并使用另一个对象的值对其进行初始化时.
  2. 按值传递对象时.

3.当一个对象按值从函数返回时.

我对 3 号有疑问如果在返回对象值时调用复制构造函数,那么如果在函数中本地声明对象,是否应该会产生问题.

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