我正在查看旧的考试问题以进行升级考试,其中一个问题是这样的:
//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-loop中创建的每个新Foo都不会调用它一次吗?
答案 0 :(得分:3)
使用new
创建对象时,需要使用delete
将其删除,以便调用析构函数并释放内存。因此,唯一会被调用析构函数的对象是a
,它会在func
结束时静态创建并销毁。
答案 1 :(得分:2)
让我们看看您的代码实际在做什么:
<%=f.input :email, input_html: { autocomplete: 'email' } %>
如您所见,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()
来实现此目的。