考虑下面的代码:
#include <iostream>
struct Person {
Person() { std::cout << "A"; } // Constructor
Person(const Person& other) { std::cout << "B"; } // Copy constructor
~Person() { std::cout << "D"; } // Destructor
};
struct Student : public Person { // Correct inheritance
Student() { std::cout << "a"; } // Constructor
Student(const Student& other) : Person(other) { std::cout << "b"; } // Copy constructor
~Student() { std::cout << "d"; } // Destructor
};
int main() {
Student* s1 = new Student; // Create Student object on heap
Student s2 = *s1; // Call copy constructor
*s1 = s2; // Use copy assignment operator
delete s1; // Delete the dynamically allocated memory
return 0;
}
输出为
AaBbdDdD
。我不明白为什么在这个例子中析构函数似乎被调用了两次。你能给我解释一下吗?
Student s2 = *s1;
不会使 s2 成为指针,因此 s2
将是一个具有自动存储功能的对象(对于大多数系统来说,这意味着:在堆栈上分配)。当您离开实例化它的范围时,该实例将被销毁。这意味着它将在 main 结束时被销毁。