Copy Constructor in C++ is called when object is returned from a function?(从函数返回对象时调用 C++ 中的复制构造函数?)
问题描述
我知道在三个实例上调用了复制构造函数
I understand copy constructor is called on three instances
- 实例化一个对象并使用另一个对象的值对其进行初始化时.
- 按值传递对象时.
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++ 中的复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从函数返回对象时调用 C++ 中的复制构造函数?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01