cppint main(){
A a;
A *p = &a;
delete p;
return 0;
}
A a produces an A object, and it seems that delete &a is right to release the memory space of a. But don’t forget that when the main() {} function ends, the local variable in it, which is a, will be automatically released. With the delete you wrote, it will be released twice, so an error will be reported.
Generally, new corresponds to delete. new is useless and delete is not needed at all. And try to ensure that new and delete are in the same code block; if you need to perform operations in two places, it is usually new in the constructor and delete in the destructor; or new in create(), Delete in delete() or release(), and pay attention to the pairing of create() and delete()...
new stores the memory of the object in 栈, that is, in user control. The memory is managed by the user, so to release the memory, use delete
And A a; stores the memory of the object in 堆, which is the system control. The release of memory is managed by the system, so using delete will report an error. The address to be released is not controllable by the user
A a
produces an A object, and it seems thatdelete &a
is right to release the memory space of a. But don’t forget that when themain() {}
function ends, the local variable in it, which is a, will be automatically released. With thedelete
you wrote, it will be released twice, so an error will be reported.Generally,
new
corresponds todelete
.new
is useless anddelete
is not needed at all. And try to ensure thatnew
anddelete
are in the same code block; if you need to perform operations in two places, it is usually new in the constructor and delete in the destructor; or new in create(), Delete in delete() or release(), and pay attention to the pairing of create() and delete()...Addresses that have not been new do not need to be deleted. New and delete should be paired
new stores the memory of the object in
栈
, that is, in user control. The memory is managed by the user, so to release the memory, usedelete
And
A a
; stores the memory of the object in堆
, which is the system control. The release of memory is managed by the system, so usingdelete
will report an error. The address to be released is not controllable by the user