What does deleting a pointer mean?

早过忘川 提交于 2020-01-21 06:33:09

问题


Is deleting a pointer same as freeing a pointer (that allocates the memory)?


回答1:


Deleting a pointer (or deleting what it points to, alternatively) means

delete p;
delete[] p; // for arrays

p was allocated prior to that statement like

p = new type;

It may also refer to using other ways of dynamic memory management, like free

free(p);

which was previously allocated using malloc or calloc

p = malloc(size);

The latter is more often referred to as "freeing", while the former is more often called "deleting". delete is used for classes with a destructor since delete will call the destructor in addition to freeing the memory. free (and malloc, calloc etc) is used for basic types, but in C++ new and delete can be used for them likewise, so there isn't much reason to use malloc in C++, except for compatibility reasons.




回答2:


You can't "delete" a pointer variable

Sure you can ;-)

int** p = new int*(new int(42));
delete *p;
delete p; // <--- deletes a pointer

But seriously, delete should really be called delete_what_the_following_pointer_points_to.




回答3:


Yes, delete is used to deallocate memory and call the destructor for the object involved.

It's common pratice to set pointer to NULL after deleting it to avoid having invalid pointers around:

Object *o = new Object();

// use object
delete o; // call o->~Object(), then releases memory
o = NULL;

When new and delete are used with standard C types in C++ source they behave like malloc and free.




回答4:


You can't "delete" a pointer variable, only set their value to NULL (or 0).




回答5:


Yes deleting a pointer is the same as deallocating memory or freeing memory, etc.




回答6:


Yes and it calls the appropriate destructor.




回答7:


In short, yes.

But you have to be careful: if you allocate with p = new sometype() only then should you use delete p. If you allocate using p = sometype[count] always use delete [] p

And one more thing: you should never pair malloc/delete or new/free.



来源:https://stackoverflow.com/questions/2449386/what-does-deleting-a-pointer-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!