There are only three types of pointer values you can pass as the operand of delete
:
- Null pointer values. They simply get ignored.
- A complete scalar (not array) object previously allocated with
new
, either of:
- The exact pointer returned by
new
- A pointer to a base subobject of the pointer returned by
new
, if and only if the base subobject's type has a virtual
destructor
Any these pointer values should NEVER ever be passed to scalar delete
:
- The result of array
new
or new[]
(use delete[]
instead)
- The result of
malloc
or any other allocator which is not new
- The address of an object with automatic or static storage duration
- The address of a member subobject or array element
- Uninitialized pointer values
- Pointers to already-deleted objects
If you break this rule, you get undefined behavior. That means your program might crash with a nice message that an invalid delete was detected. Or your data might get corrupted, saved in your data files, sent to your boss, shown to the customer, and later you get fired. So don't break the rule.
Your code falls into category "NEVER DO THIS #4".
The reason it works this way is because an implementation can (and most do) track extra information called metadata along with each allocated block. For example, the size of the block, which is pretty important for enabling reuse. There is no metadata for part of a block, and there may not be any way to find the metadata from a pointer into the middle.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…