# 关于编译器对连续的构造+拷贝构造/连续的拷贝构造的优化

``````// 《深度探索C++对象模型》
Weight f(Weight u)
{
Weight v(u);
Weight w = v;

return w;
}

int main()
{
Weight x;
Weight ret = f(f(x));
return 0;
}
``````

• 1 匿名对象
• 2.匿名对象的用处
• 3.题解
• 3.1 铺垫
• 3.2 解题

# 1 匿名对象

``````#include
using std::cout;
using std::cin;
using std::endl;

class Weight
{
public:
Weight()
{
cout << "Weight()" << endl;
}

Weight(const Weight& w)
{
cout << "Weight(const Weight& w)" << endl;
}

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

Weight& operator=(const Weight& w)
{
cout << "Weight& operator=(const Weight& w)" << endl;
return *this;
}

void print()
{
cout << "2022-5-25" << endl;
}
};

// 《深度探索C++对象模型》
Weight f(Weight u)
{
Weight v(u);
Weight w = v;

return w;
}

int main()
{
Weight x;
Weight();
f(x);
return 0;
}
``````

# 2.匿名对象的用处

``````class A
{
public:
A(int x)
{}
};

int main()
{
A a1(1);
A a2 = 2; // A(2)  -> A a2(A(2))   优化:直接构造
return 0;
}
``````

# 3.题解

## 3.1 铺垫

ok，我们先自己来算一下。
x传参拷贝构造`1`次，33、34行各拷贝构造`1`次，传值返回拷贝构造`1`次，41返回的结果又拷贝构造给ret，又是`1`次。是不是应该总共`5`次呀！

ok，我们看运行结果：