c++ - Deleting void pointer after assigning it with original type -
is ok delete void pointer in below program.
class sample { public: int intval; float floatval; }; main() { sample *samobj = new sample(); void *vptr = samobj; delete vptr; }
this sample program have written. actually, in project have no other way doing similar thing. similar code in .h interface file, , when include file , compile other components, compiler gives warning message "warning: deleting 'void*' undefined", doubt since have assigned void pointer sample object type, isn't safe delete pointer?
calling delete on void pointer undefined behavior[ref ]. should not @ all. not calling delete
on void pointer on pointer of type sample
fine.
[ref ] c++ standard :section 5.3.5/3:
in first alternative (delete object), if static type of operand different dynamic type, static type shall base class of operand’s dynamic type , 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.
footnote:
this implies object cannot deleted using pointer of type void* because there no objects of type void
Comments
Post a Comment