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

邮差的信 提交于 2019-11-29 17:45:45

问题


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;

回答1:


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.




回答2:


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).




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16527829/is-it-considered-good-style-to-dereference-new-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!