当使用复制构造函数为持有它的变量分配一个新对象时,前一个对象是否被销毁?
Is the previous object destroyed when the variable holding it gets assigned a new one using a copy constructor?
看看这段代码:
#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
打印在屏幕就像从未调用过析构函数一样。
Is the previous object destroyed when the variable holding it gets assigned a new one using a copy constructor?
这个问题没有实际意义,因为不可能这样做。
当你运行
object_a = object_b;
这会调用赋值运算符(不是复制构造函数)。它不会创建或销毁任何对象(除非您的赋值运算符这样做)。
在这种情况下,您没有定义赋值运算符,因此使用默认运算符,它会用另一个对象的 ID(即 4)覆盖 object_3
的 ID。因此,当 object_3
被销毁时,它会打印 "Object with id 4 has been destroyed".
看看这段代码:
#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
打印在屏幕就像从未调用过析构函数一样。
Is the previous object destroyed when the variable holding it gets assigned a new one using a copy constructor?
这个问题没有实际意义,因为不可能这样做。
当你运行
object_a = object_b;
这会调用赋值运算符(不是复制构造函数)。它不会创建或销毁任何对象(除非您的赋值运算符这样做)。
在这种情况下,您没有定义赋值运算符,因此使用默认运算符,它会用另一个对象的 ID(即 4)覆盖 object_3
的 ID。因此,当 object_3
被销毁时,它会打印 "Object with id 4 has been destroyed".