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:

  1. you delete pointer-to-base,

  2. 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 of delete 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 allocated new, 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 cv void (5.4). expression of type void shall used expression statement (6.2), operand of comma expression (5.19), second or third operand of ?: (5.16), operand of typeid, noexcept, or decltype, expression in return statement (6.6.3) function return type void, or operand of explicit conversion type cv void.


also, unless you're interfacing c api, void* should strive avoid completely.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -