首先,先介绍以下拷贝构造和构造的区别。
拷贝构造Date(Date& d)初始化:用一个实例对象去初始化一个未初始化的对象,
例:如果d1未被实例化,则Date d1 = d2; 也会被编译器认为拷贝构造,进而调用Date(Date& d);
构造Date(int year=0,int month =0,int day = 0)。
赋值运算符重载指的是用已经实例化的类去赋值给另一个已经实例化的类。
1.优化是怎么进行的
优化在于编译器,省略创建临时变量,直接将返回值传回调用函数所在的行中。重点记住连续拷贝构造+赋值重载时无法优化,要一步步进行。

2.优化结果




2.1代码
#include<iostream> 
using namespace std;
class A
{
public:
    A(int a = 0)
        :_a(a)
    {
        cout << "A(int a)" << endl;
    }
    A(const A& aa)
        :_a(aa._a)
    {
        cout << "A(const A& aa)" << endl;
    }
    A& operator=(const A& aa)
    {
        cout << "A& operator=(const A& aa)" << endl;
        if (this != &aa)
        {
            _a = aa._a;
        }
        return *this;
    }
    ~A()
    {
        cout << "~A()" << endl;
    }
private:
    int _a;
};
void f1(A aa)
{	
} 
void f2()
{
	A aa;
	return aa;
}
void  Func1(A aa)
{
}
void Func2(const A& aa)
{
}
//
//A Func3()
//{
//	A aa;
//	return aa;
//}
//
//A& Func4()
//{
//	static A aa;
//	return aa;
//}
//int main()
//{
	A a1;
	Func1(a1);
	Func2(a1);
//	
//	//Func3(); 
//	A a1 = Func4();
//	
//	return 0;
//}
//A Func5()
//{
//	A aa;
//	return aa;
//}
int main()
{
//	A ra1 = Func5();  //拷贝构造+拷贝构造--》优化为拷贝构造
//	cout <<"=============="<<endl;
//	A ra2;
//	ra2 = Func5();
	
//	A aa1;
//    Func1(aa1); 
	// 不会优化,因为函数形参没有引用,会使用拷贝构造 
	Func1(1);
	
	
//	Func1(A(1)); // 构造+拷贝构造 ->优化为构造
//    Func1(1);    // 构造+拷贝构造 ->优化为构造
//	A aa2 = 1;  // 构造+拷贝构造 ->优化为构造
	
	return 0; 
} 
3.explicit
当调用的函数使用explicit修饰时,无法优化的同时会报错,因此在在此时调用函数无法进行隐式类型转换。如:
下面explicit的作用和用法:
1. -- 禁止隐式类型转换
2. -- 使用explicit关键字注意事项
explicit关键字只能用于类内部的构造函数声明上,在类的定义体外部所做的定义上不在重复它
下面是使用案例:
#include<iostream> 
using namespace std;
class A
{
public:
    explicit A(int a = 0)
        :_a(a)
    {
        cout << "A(int a)" << endl;
    }
    A(const A& aa)
        :_a(aa._a)
    {
        cout << "A(const A& aa)" << endl;
    }
    A& operator=(const A& aa)
    {
        cout << "A& operator=(const A& aa)" << endl;
        if (this != &aa)
        {
            _a = aa._a;
        }
        return *this;
    }
    ~A()
    {
        cout << "~A()" << endl;
    }
private:
    int _a;
};
void  Func1(A aa)
{
}
int main()
{
	Func1(1);
	return 0; 
}
 
编译时会报错,说明无法进行隐式转换
![]()



















