Optimization issues when copying objects in c++

The blogger tested based on VS2019, and different compilers may have different conditions.

Consider the following category A:

class A
{
    
    
public:
	A(int a = 0)
		:_a(a)
	{
    
    
		cout << "A(int a = 0)" << endl;
	}

	A(const A& aa)
		:_a(aa._a)
	{
    
    
		cout << "~A(const A& aa)" << endl;
	}

	~A()
	{
    
    
		cout << "~A()" << endl;
	}

	A& operator= (const A& aa)
	{
    
    
		cout<<"	A& operatoor = (const A & aa)" <<endl;
		if (this != &aa)
		{
    
    
			_a = aa._a;
		}

		return *this;
	}

private:
	int _a;
};




void f1(A aa)
{
    
    }

A f2()
{
    
    
	A aa;
	return aa;
}

Example analysis

Only passing parameters by value

// 传值传参
A aa1;
f1(aa1);
cout << endl;    //一次构造,一次拷贝构造

Insert image description here


Direct optimization example:


// 隐式类型,连续构造+拷贝构造->优化为直接构造
f1(1); 

Insert image description here


// 一个表达式中,连续构造+拷贝构造->优化为一个构造
f1(A(2));    
cout << endl;

Insert image description here

Return by value


// 传值返回
f2();    //   1次 构造一次 + 1次 拷贝构造
cout << endl;

Insert image description here

Logically speaking, it is 1 construction + 2 copy constructions, but when the compiler encounters this kind of continuous copy construction, it will automatically optimize into 1 copy construction.


	// 一个表达式中,连续拷贝构造->优化为一个拷贝构造
	A aa1 = f2();
	cout << endl;

Insert image description here

Insert image description here


// 一个表达式中,连续拷贝构造+赋值重载->无法优化
A aa1;
aa1 = f2();
cout << endl;

Insert image description here
Insert image description here

An example question

void f1(A aa)
{
    
    }

A f2()
{
    
    
	A aa;
	return aa;
}
A f(A u)
{
    
    
	A v(u);
	A w = v;
	return w;
}
int main()
{
    
    
	A x;
	A y = f(f(x));
}

How many times have the constructor and copy constructor been called?
1 construction and 7 copy construction

Insert image description here
The calling example is shown in the figure:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/132847521