【问题标题】:Why there is no temporary object when returning an object through the constructor?为什么通过构造函数返回对象时没有临时对象?
【发布时间】:2018-03-28 02:41:12
【问题描述】:

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

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.

所以我的问题是:

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

【问题讨论】:

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


【解决方案1】:
Stonewt operator-(const Stonewt & obj1, const Stonewt & obj2)
{
    ...
    return obj1;
}

 

   incognito = incognito - wolfe;

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

【讨论】:

  • 我以为临时对象是默认构造函数创建的,所以我添加了“cout
  • @LeoHu,那是因为使用了默认的复制构造函数。实现一个拷贝构造函数,它会被调用。
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 2013-08-29
  • 2023-04-04
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多