C++ 中的复制构造函数 当从函数返回对象时调用?
会在三个实例上调用复制构造函数
- 我知道在实例化一个对象并使用另一个对象的值对其进行初始化时,
- 。 按值传递对象时。
3. 当一个对象按值从函数返回时。
我对第 3 点有疑问 如果在返回对象值时调用复制构造函数,并且在函数中本地声明对象,那么它不会产生问题吗?
我的意思是复制构造函数是深复制构造函数,并将对象的引用作为参数
I understand copy constructor is called on three instances
- When instantiating one object and initializing it with values from another object.
- 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
调用它完全是为了避免出现问题。 作为结果的新对象从本地定义的对象初始化,然后本地定义的对象被销毁。
对于深复制用户定义的构造函数来说,它们都是一样的。 首先为将作为结果的对象分配存储空间,然后调用复制构造函数。 它使用传递的引用来访问本地定义的对象并将所需内容复制到新对象。
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.
复制在被调用函数退出之前完成,并将当时存在的局部变量复制到返回值中。
被调用的函数可以访问返回值将占用的内存,即使在进行复制时该内存不在“范围内”,它仍然可用。
The copy is done before the called function exits, and copies the then-existing local variable into the return value.
The called function has access to the memory the return value will occupy, even though that memory is not "in scope" when the copy is being made, it's still available.
根据对我的问题的回答,复制构造函数<甚至可以调用两次:一次将本地对象复制到返回“对象”上,一次将返回对象复制到它所分配的变量上。
然而,它不必! 编译器可以优化这两种复制结构。
According to an answer to my question, the copy constructor may be called even twice: once to copy a local object onto the return 'object', and once to copy the return object onto the variable it was assigned to.
However, it needn't be! The compiler can optimize both copy constructions away.
不,它在当地人被摧毁之前调用它。 您可以使用记录破坏和复制构造的对象或通过查看生成的汇编代码来测试这一点。
No, it calls it before the locals are destroyed. You can test this with an object that logs destruction and copy construction, or by looking at the generated assembly code.
调用复制构造函数的一般情况有以下三种情况:
There are three general cases where the copy constructor is called: