为什么通过构造函数返回对象时没有临时对象?
Why there is no temporary object when returning an object through the constructor?
我想弄清楚通过构造函数(转换函数)返回对象时到底发生了什么。
Stonewt::Stonewt(const Stonewt & obj1) {
cout << "Copy constructor shows up." << endl;
}
Stonewt::Stonewt(double lbs) {
cout << "Construct object in lbs." << endl;
}
Stonewt::~Stonewt() {
cout << "Deconstruct object." << endl;
}
Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2) {
double pounds_tmp = obj1.pounds - obj2.pounds;
return Stonewt(pounds_tmp);
}
int main() {
Stonewt incognito = 275;
Stonewt wolfe(285.7);
incognito = wolfe - incognito;
cout << incognito << endl;
return 0;
}
Output:
Construct object in lbs.
Construct object in lbs.
Construct object in lbs.
Deconstruct object.
10.7 pounds
Deconstruct object.
Deconstruct object.
所以我的问题是:
为什么通过构造函数返回对象时没有拷贝构造函数(没有临时对象)?
Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
{
...
return obj1;
}
incognito = incognito - wolfe;
您的 operator - ()
正在返回 incognito
的副本,然后您将其分配给 incognito
。然后销毁副本。
我想弄清楚通过构造函数(转换函数)返回对象时到底发生了什么。
Stonewt::Stonewt(const Stonewt & obj1) {
cout << "Copy constructor shows up." << endl;
}
Stonewt::Stonewt(double lbs) {
cout << "Construct object in lbs." << endl;
}
Stonewt::~Stonewt() {
cout << "Deconstruct object." << endl;
}
Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2) {
double pounds_tmp = obj1.pounds - obj2.pounds;
return Stonewt(pounds_tmp);
}
int main() {
Stonewt incognito = 275;
Stonewt wolfe(285.7);
incognito = wolfe - incognito;
cout << incognito << endl;
return 0;
}
Output:
Construct object in lbs.
Construct object in lbs.
Construct object in lbs.
Deconstruct object.
10.7 pounds
Deconstruct object.
Deconstruct object.
所以我的问题是:
为什么通过构造函数返回对象时没有拷贝构造函数(没有临时对象)?
Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
{
...
return obj1;
}
incognito = incognito - wolfe;
您的 operator - ()
正在返回 incognito
的副本,然后您将其分配给 incognito
。然后销毁副本。