operator delete
The complement to the new-expression is the delete-expression, which first calls the destructor and then releases the memory (often with a call to free( )). Just as a new-expression returns a pointer to the object, a delete-expression requires the address of an object.
delete fp;
This destructs and then releases the storage for the dynamically allocated MyType object created earlier.
delete can be called only for an object created by new. If you malloc( ) (or calloc( ) or realloc( )) an object and then delete it, the behavior is undefined. Because most default implementations of new and delete use malloc( ) and free( ), you’d probably end up releasing the memory without calling the destructor.
If the pointer you’re deleting is zero, nothing will happen. For this reason, people often recommend setting a pointer to zero immediately after you delete it, to prevent deleting it twice. Deleting an object more than once is definitely a bad thing to do, and will cause problems.
因此,在使用指针时,free或delete掉后紧接着将其置为空,以免将其再次free
本文介绍了C++中new表达式与delete表达式的使用方法。new分配内存并调用构造函数,返回指向对象的指针;delete则先调用析构函数再释放内存。不当使用可能导致未定义行为,例如对非new创建的对象使用delete,或者重复删除同一对象。文章还建议删除对象后将指针设为零以避免重复删除。
1293

被折叠的 条评论
为什么被折叠?



