什么是C ++的“删除”运营商实际上做什么?
问题描述:
我认为它释放了先前分配的内存,但我可能错了:
I thought that it freed previously allocated memory, but I may be wrong:
class Person {
public:
Person(string, int, double);
~Person();
int age;
string name;
double weight;
};
int main() {
Person* p = new Person("Jane", 20, 130);
cout << p->age; // prints 20
delete p;
cout << p->age; // prints 20 again...
}
答
这是未定义的行为。
释放/删除内存不意味着它将被清零,它只意味着该内存可以再次用于未来的分配。
Freeing/Deleting the memory does not mean it will be zeroed, it only means that that memory can be used again for future allocations. You should never try to use freed/deleted memory.
使用 delete
大于 free
,如果不适当地转换,它也会调用你的变量的析构函数。
With the delete
case over free
, it will also call the destructor of your variable if not casted improperly.