![](/img/trans.png)
[英]why copy constructor is getting called even though I am actually copying to already created object in C++?
[英]How values of member variables are getting copied even though copy constructor is not getting called due to RVO in C++
即使在以下程序中未调用构造函数,我也无法理解如何复制成员变量的值。
#include <iostream>
using namespace std;
class myclass
{
public:
int x;
int y;
myclass(int a, int b)
{
cout << "In Constructor" << endl;
x = a;
y = b;
}
~myclass()
{
cout << "In Destructor" << endl;
}
myclass(const myclass &obj)
{
cout << "In Copy Constuctor " << obj.x << " " << obj.y << endl;
x = obj.x;
y = obj.y;
}
myclass &operator=(const myclass &obj)
{
cout << "In Operator Overloading" << obj.x << obj.y << endl;
x = obj.x;
y = obj.y;
return *this;
}
};
int main()
{
myclass obj1 = myclass(2, 3);
cout << "obj1.x : " << obj1.x << "obj1.y" << obj1.y << endl;
}
Output:
In Constructor
obj1.x : 2obj1.y3
In Destructor
我了解到,由于返回值优化,未调用副本构造函数。 但是我不了解obj1如何获取值2和3。请问有人可以帮助我理解这一点,或者返回值优化如何在后台工作。
这些值不会被复制,因为它们不需要被复制。 而是将原本要复制的值初始化。 复制省略意味着编译器从本质上解决了这个问题:
myclass obj1 = myclass(2, 3);
变成这个:
myclass obj1(2, 3);
因此,没有构造任何需要复制的额外对象。
请注意,您所提到的RVO是复制省略的一种形式。 但是复制省略的这种特定情况不是RVO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.