取消引用new指针是否被认为是好的样式? [英] Is it considered good style to dereference `new` pointer?

查看:71
本文介绍了取消引用new指针是否被认为是好的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为避免继续使用->而直接使用该对象,是否可以这样做?

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. 内存泄漏(很可能,除非您使用的是从提供的代码中看不到的模式),因为obj将存储由副本 >表达式,并且new返回的指向该对象的指针丢失;
  2. 最重要的是,未定义的行为,因为您要向delete传递未使用new分配的对象的指针.根据C ++ 11标准第5.3.5/2段:
  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:

[...]在第一个替代方案(删除对象)中,删除操作数的值可以为空指针 值,指向由先前的 new-expression 创建的非数组对象的指针或指向子对象的指针(1.8) 表示此类对象的基类(第10条). 如果不是,则行为是不确定的.

[...] 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.

这篇关于取消引用new指针是否被认为是好的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆