为什么在通过构造函数返回对象时没有临时对象?

时间:2018-03-28 02:41:12

标签: c++ destructor temporary-objects copy-elision

我试图找出通过构造函数(转换函数)返回对象时究竟发生了什么。

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.

所以我的问题是:

为什么在通过构造函数返回对象时没有复制构造函数(没有临时对象)?

1 个答案:

答案 0 :(得分:3)

Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
{
    ...
    return obj1;
}

   incognito = incognito - wolfe;

您的operator - ()正在返回incognito的副本,然后您将其分配给incognito。然后销毁该副本。