当使用复制构造函数为其保留变量时,前一个对象是否被销毁?

时间:2016-07-28 04:24:22

标签: c++ destructor

看看这段代码:

#include <iostream>
using namespace std;

class A {
    private:
        int _x;
        int _id;
        static int count;
    public:
        A(int x) : _x(x) {
            this->_id = A::count++;
            cout << "Object with id "      << this->_id
                 << " has been created."   << endl;
        }
        ~A() {
            cout << "Object with id "      << this->_id
                 << " has been destroyed." << endl;
        }

        int get_x(void) {
            return this->_x;
        }

        A add(A& object) {
            A tmp(this->_x + object._x);
            return tmp;
        }
};

int A::count = 1;

int main(void) { 
    A object_1(13);
    A object_2(5);
    A object_3(12);

    object_3 = object_1.add(object_2);

    cout << object_3.get_x() << endl;


    return 0;
}

以下是该计划的输出:

Object with id 1 has been created.
Object with id 2 has been created.
Object with id 3 has been created.
Object with id 4 has been created.
Object with id 4 has been destroyed.
18
Object with id 4 has been destroyed.
Object with id 2 has been destroyed.
Object with id 1 has been destroyed.

我不明白ID为3的对象发生了什么变化?它绝对是创造出来的,但是我看不出有任何线条告诉我它曾经被摧毁过。你能告诉我这里发生了什么吗?

作为一个旁白的问题,为什么当我使用return 0时,析构函数工作正常,但当我使用exit(EXIT_SUCCESS)时,我没有看到Object with # has been destroyed在屏幕上打印为虽然析构函数从未被调用过。

1 个答案:

答案 0 :(得分:4)

  

当使用复制构造函数为其保留变量时,前一个对象是否被销毁?

这个问题没有实际意义,因为无法这样做。

运行时

object_a = object_b;

这会调用赋值运算符(而不是复制构造函数)。它不会创建或销毁任何对象(除非您的赋值运算符执行此操作)。

在这种情况下,您尚未定义赋值运算符,因此使用默认值,它会用另一个对象的ID(即4)覆盖object_3的ID。因此,当object_3被销毁时,它会打印出“id为4的对象已被破坏”。