[英]How values of member variables are getting copied even though copy constructor is not getting called due to RVO in C++
I am not able to understand how the values of member variables are getting copied even though the constructor is not getting called in the below program. 即使在以下程序中未调用构造函数,我也无法理解如何复制成员变量的值。
#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
I understood that due to Return Value Optimization, copy constructor is not getting called. 我了解到,由于返回值优化,未调用副本构造函数。 But I didn't understand how obj1 is getting values 2 and 3. Can any one please help me to understand this or how Return Value Optimization will work behind the scenes.
但是我不了解obj1如何获取值2和3。请问有人可以帮助我理解这一点,或者返回值优化如何在后台工作。
The values aren't getting copied, because they don't need to be copied. 这些值不会被复制,因为它们不需要被复制。 Instead, the values which would have been copied are initialized in place.
而是将原本要复制的值初始化。 Copy elision means that the compiler essentially turns this:
复制省略意味着编译器从本质上解决了这个问题:
myclass obj1 = myclass(2, 3);
Into this: 变成这个:
myclass obj1(2, 3);
So no extra object is constructed which needs to be copied. 因此,没有构造任何需要复制的额外对象。
Note that RVO, which you've referred to, is a form of copy elision. 请注意,您所提到的RVO是复制省略的一种形式。 But this specific case of copy elision is not RVO.
但是复制省略的这种特定情况不是RVO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.