[英]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.