Search code examples
c++pointersnew-operatordereference

Is it considered good style to dereference `new` pointer?


To avoid keep having to use -> and instead work directly with the object, is it acceptable practice to do:

obj x = *(new obj(...));
...
delete &obj;

Solution

  • This is not just poor practice, but:

    1. Leaking memory (most likely, unless you are using some pattern that is not visible from the code you provided), since obj will store a copy of the original object created by the new expression, and the pointer to that object returned by new is lost;
    2. Most importantly, undefined behavior, since you are passing to delete a pointer to an object that was not allocated with new. Per paragraph 5.3.5/2 of the C++11 Standard:

    [...] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.