从函数返回对象时调用 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.
相关文章