默认情况下,按值return'ing 对象将从源对象复制构造一个临时对象,然后将该临时对象传递给调用者。换句话说,语句d3 = d1 + d2;基本上是这样做的:
date implicit_temp(operator+(d1, d2));
d3 = implicit_temp;
这在幕后分解为以下逻辑:
// The + operator
date temp; // The default constructor
temp.day = d1.day + d2.day;
temp.month = d1.month + d2.month;
temp.year = d1.year + d2.year;
// return temp;
date implicit_temp(temp); // The copy constructor
temp.~date(); // Destructor
// Assignment operator
d3.day = implicit_temp.day;
d3.month = implicit_temp.month;
d3.year = implicit_temp.year;
implicit_temp.~date(); // Destructor
它与您看到的输出顺序相同。
如果编译器支持 RVO(返回值优化),它将能够优化语句date创建的临时对象,通过传递一个隐藏参数,因此可以通过其运算符直接分配变量,使代码行为好像它是这样写的:returnd3returntempd3=
void date::operator+(const date& other, date& result) const
{
date temp;
temp.day=day+other.day;
temp.month=month+other.month;
temp.year=year+other.year;
result = temp;
}
这将在引擎盖下分解为这个逻辑:
// The + operator
date temp; // The default constructor
temp.day = d1.day + d2.day;
temp.month = d1.month + d2.month;
temp.year = d1.year + d2.year;
// return temp; - Assignment operator
d3.day = temp.day;
d3.month = temp.month;
d3.year = temp.year;
temp.~date(); // Destructor