简体   繁体   中英

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;

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 .

No, and in fact this leads to a leak. x is copy initialized , so the original object pointed to by new obj is lost.

Just use

obj x(...);

No need for dynamic allocation. Or

obj x = obj(...);

if you must (doubt it).

Certainly not; that copies the dynamic object to an automatic variable, loses the only pointer to it, and then attempts to delete the automatic copy. You've got a memory leak and an invalid deletion.

Much better would be to use an automatic variable in the first place:

obj x(...);
...
// no need to delete anything

or, if it really must be dynamic for some reason (because it's too big for the stack, or you don't always want to destroy it here), then use a smart pointer, and a reference if you really don't like ->

std::unique_ptr<obj> p(new obj(...));
obj & x = *p;
...
// still no need to delete anything

Changing your x into a reference would be valid (as long as you're careful that exceptions, early function returns, etc. won't cause a leak), but would cause howls of confusion among anyone unfortunate enough to have to maintain it.

You cannot delete your object properly if you do it like that.

Implicitly you do the following.

class A
{
public:
  int test (void) { return 1; }
};

int main (void)
{
  A * p = new A;
  A v(*p);
  //...
  delete &v; // &v != p and v is not constructed via new!
  return 0;
}

If you want to work with an object-like-syntax you can bind a reference to the object.

class A
{
public:
  int test (void) { return 1; }
};

int main (void)
{
   A * p = new A;
   A & r = *p;
   int i = r.test();
   delete p;
   return 0;
}

If you delete your object through the same pointer, there will be no leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM