Return class 析构函数

Return class destructor

我是一名学生,正在学习 C++。我相当擅长 C++,但 "simple" 事情让我纠结。我最近学习了 classes、方法、constructor/deconstructor、继承、虚拟等。我有这段代码:

#include <iostream>
using namespace std;

class test {
    int a, c;
public:
    test() { cout << "Constructor\n"; }
    test(int a) :a(a) { cout<<"Explicit Constructor\n"; }
    test foo(const test&, const test&);
    ~test() { cout << "DECONSTRUCTOR!\n"; }
};

test test::foo(const test &t1, const test &t2) {
    test rez;
    rez.c = t1.a + t2.a;
    return rez;
}

void main() {
    test t1(5), t2(21), rez;
    rez.foo(t1, t2);
    cin.ignore();
}

我知道在 foo 中我创建了一个本地 class,当它超出范围时会被删除。所以当 foo 被调用时,我应该看到一个构造函数和一个析构函数,但它又给了我一个解构函数,所以我有一个构造函数用于两个析构函数。

您忘记实现复制构造函数了:

test(const test &rhs)
{
  cout << "Constructor";
}

它被用来将 rez 对象复制回 foo

的调用者

为您的class test再添加一种方法:

test(test const &) { cout << "Copy constructor" << endl; }

看看接下来会发生什么。

参考评论:

test test::foo(const test &t1, const test &t2) {
    test rez;
    // constructor for rez invoked
    rez.c = t1.a + t2.a;
    return rez;
    // destructor for rez invoked
}

void main() {
    test t1(5), t2(21), rez;
    // 3 constructor invocations
    rez.foo(t1, t2);
    // constructor for return value is called
    // but you are missing it since you did not implement copy constructor
    // destructor for return value is called
    // as you did not use it
    cin.ignore();
    // 3 destructor invocations
}