c++ - Is it safe to delete memory with a pointer of different type than the used in new? -
is following code safe? there reference c++ standard addressing question?
// somestruct pod: no constructors or destructor somestruct *pss = new somestruct(); void *pv = reinterpret_cast<void*>(pss); delete pv;
this ok when:
you delete pointer-to-base,
and base class has virtual destructor.
otherwise, you're in land of illegal code , undefined behaviour.
c++14 5.3.5/2
if operand has class type, operand converted pointer type calling above-mentioned conversion function, , converted operand used in place of original operand remainder of section. in first alternative (delete object), value of operand of
delete
may null pointer value, pointer non-array object created previous new-expression, or pointer subobject (1.8) representing base class of such object (clause 10). if not, behavior undefined. in second alternative (delete array), value of operand ofdelete
may null pointer value or pointer value resulted previous array new-expression. if not, behavior undefined. [ note: means syntax of delete-expression must match type of object allocatednew
, not syntax of new-expression. — end note ] [ note: pointer const type can operand of delete-expression; not necessary cast away constness (5.2.11) of pointer expression before used operand of delete-expression. — end note ]
c++14 5.3.5/3
in first alternative (delete object), if static type of object deleted different dynamic type, static type shall base class of dynamic type of object deleted , static type shall have virtual destructor or behavior undefined. in second alternative (delete array) if dynamic type of object deleted differs static type, behavior undefined.
additionally, void
incomplete type (c++14 3.9.1/9):
the
void
type has empty set of values.void
type incomplete type cannot completed. used return type functions not return value. expression can explicitly converted type cvvoid
(5.4). expression of typevoid
shall used expression statement (6.2), operand of comma expression (5.19), second or third operand of?:
(5.16), operand oftypeid
,noexcept
, ordecltype
, expression in return statement (6.6.3) function return typevoid
, or operand of explicit conversion type cvvoid
.
also, unless you're interfacing c api, void*
should strive avoid completely.
Comments
Post a Comment