0

在书中,我遇到过这样的情况,“当一个对象被函数返回时,会自动创建一个临时对象来保存返回值。函数实际返回的是这个对象。返回值后,这个物体被摧毁了。”

我无法完全理解这里所说的确切内容。

// Returning objects from a function.
#include <iostream>
using namespace std;

class myclass 
{
    int i;

    public:

    myclass()
    {
        cout << "constructing: " << i << endl;
    }

    ~myclass()
    {
        cout << "destructing: " << i << endl;
    }

    void set_i(int n) { i=n; }
    int get_i() { return i; }
};

myclass f(); // return object of type myclass

int main()
{
    myclass o;
    o = f();

    cout << o.get_i() << "\n";
    return 0;
}

myclass f()
{
    myclass x;
    x.set_i(1);
    return x;
}

上面的程序给出以下输出。

constructing: 0
constructing: 3935896
destructing: 1
1
destructing: 1

我的问题是:

当 f() 返回 "x" 时,根据本书应该已经创建了一个临时对象。但是,不会打印“constructing:”,因为正在创建“x”的副本,因此调用构造函数是多余的(这与将对象传递给函数时仅调用其析构函数的原因相同) .

但是,当那个临时对象被销毁时,为什么不调用它的析构函数呢?

4

0 回答 0