为什么析构函数在这里只被调用一次?

Why is the destructor only called once here?

我正在为即将到来的考试翻阅旧题,其中一题是这样的:

//How many times is Foo's destructor called when func() is called?
void func(){
    Foo a;
    for (int i = 0; i < 10; i++){
        Foo *c = new Foo();
        a = *c;
    }
}

正确答案是 1。任何人都可以向我解释为什么在 for 循环中创建的每个新 Foo 都不会被调用一次吗?

当您使用 new 创建一个对象时,您需要使用 delete 删除它以便调用析构函数并释放内存。因此,唯一会调用其析构函数的对象是 a,它是静态创建的,并在 func 结束时销毁。

让我们看看您的代码实际做了什么:

void func(){
    Foo a; // Creates an object in the stack that will be destroyed once the function scope is no longer valid (meaning, when the function call is finished).
    for (int i = 0; i < 10; i++){
        Foo *c = new Foo(); // this line allocates memory for a new object and stores a pointer to that memory in 'c'
        a = *c; // Makes a field-by-field copy (to put it simple) of the memory pointed by c into the object a. No new memory is allocated, no memory is destroyed
    }
}

如您所见,new Foo() 分配的内存从未被销毁,您需要在某个时候调用 delete c; 来实现。