C++ - operator delete confusion
I am in the process of learning C++ and am new to the delete operator. As you can see from the code I am applying the delete operator to the new operator (m). After applying it though I am still able to to use the pointer开发者_开发百科 and assign it a new value. I am not receiving any compiler errors. From what I have read, I should not be able to use the new pointer after applying delete because the pointer doesn't point to anything. Any help is welcome. Thank you.
int main()
{
int* m;
m = new int;
*m = 14;
cout << *m << " ";
delete m;
*m = 12;
cout << *m;
}
Console Ouput
14 12
The delete operator is a bit subtle. When you write
delete m;
The meaning of this code is "reclaim the memory that m
is pointing at." In other words, it does not do anything to the pointer m
, but rather to the object m
points at. For example, in this diagram:
+-----+
m --> | 137 |
+-----+
The pointer m
is pointing at an integer with value 137. If you write delete m
, then the memory holding 137
is reclaimed, but m
itself is untouched. You can reassign it to point to other objects, or to NULL
, but you shouldn't continue referencing the value it used to point at because it no longer exists.
The compiler doesn't check this. Tools like lint check this. Yes, sometimes you can get away with using deleted memory, but it's undefined behavior. The memory doesn't belong to you anymore, and so you risk writing memory being used by another object in you program. It's only because your program is so simple that this doesn't happen.
That's right, your code is incorrect.
After delete m;
, the pointer m
does no longer point to a valid int
variable in memory. So whenever you dereference this pointer after that, you get undefined behaviour - your program will behave in an unpredictable way, likely causing bugs.
BTW- some compilers help you to find such errors in code by filling the "deleted" values (not pointers) with characteristic values, like 0xFEEEFEEE
. This allows you to notice during debugging that you're trying to use a pointer which points to deleted memory.
After calling delete m
, the memory that m
used to point to has been deallocated and may be reallocated by the system. m
, however, still points to that location, which means if you choose to use/dereference it again, you might get the values you want. You might not. It is undefined behavior.
Using a pointer after delete'ing it is "undefined". It may work. It may not. It is almost certainly a really bad thing to do (tm).
精彩评论