#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base() :selfid(++n) {cout << "Base() " << selfid << endl;}
Base(const Base& other) :selfid(++n){cout << "Base(" << selfid << ") copy from " << other.selfid << endl;}
Base& operator=(const Base& other){ cout << "Base(" << selfid << ") = " << other.selfid << endl; return *this;}
virtual ~Base(){cout << "~Base(" << selfid << ") destroyed" << endl;}
public:
int selfid;
static int n;
};
int Base::n = 0;
Base Test()
{
Base b;//b Base() 2 e Base() 3
return b;
}
int main()
{
Base b1;//a Base() 1
b1 = Test();//c Base(1) = 2,d ~Base(2) destroyed
Base c(Test());//3
std::cout << c.selfid << endl;
//f ~Base(3) destroyed ,~Base(1) destroyed
return 0;
}
可以看出在函数第二次调用图Test()来构造c的时候,整个过程只构造了一个对象。优化的还是很厉害的。

本文深入探讨了C++中构造函数的使用及其优化效果,通过具体代码示例展示了当从函数返回局部对象并直接构造另一个对象时,编译器如何进行优化,仅创建一个对象而非两个,从而提高效率。
1万+

被折叠的 条评论
为什么被折叠?



