c++ - Is it considered good style to dereference `new` pointer? -
to avoid keep having use ->
, instead work directly object, acceptable practice do:
obj x = *(new obj(...)); ... delete &obj;
this not poor practice, but:
- leaking memory (most likely, unless using pattern not visible code provided), since
obj
store copy of original object creatednew
expression, , pointer object returnednew
lost; - most importantly, undefined behavior, since passing
delete
pointer object not allocatednew
. per paragraph 5.3.5/2 of c++11 standard:
[...] 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.
Comments
Post a Comment