`delete []`不是`new []`的对应物吗? [英] Isn't `delete[]` the counterpart to `new[]`?

查看:136
本文介绍了`delete []`不是`new []`的对应物吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了阅读有关工厂模式的在线信息,我正在阅读将近20年的C ++知识.最终的使用上下文可能会使用不同的第三代语言(3GL),但是由于我过去的经验,我认为遵循C ++比(说)Java更容易,尽管后者的语法可能不太复杂.但是,更大的原因是,我可以找到要解决的问题的唯一代码示例是C ++,即在没有工厂模式的情况下.大多数帖子都在高层叙事中讨论了模式的原因,然后提供代码来显示模式的机制,而不是在没有模式的情况下显示问题.

I'm reading to brush up on C++ knowledge that is almost 2 decades old in order to understand online info on the factory pattern. The final usage context will likely be in a different 3rd generation language (3GL), but because of my past experience, I think it's easier to follow C++ than (say) Java, even though the latter may be less intricate in syntax. A bigger reason, however, is that the only code example I can find of the problem being addressed, i.e., in the absence of the factory pattern, is in C++. Most posts talk about the reasons for the pattern in high level narrative, then provide code to show the mechanics of the pattern instead of the problem in the absence of the pattern.

我正在研究的代码位于此处.我很难理解使用delete[]销毁使用new创建的对象的事实.根据各种读数,deletenew一起使用,并且delete[]new[]一起使用.但是,在远离C ++这么长时间之后,我很容易忽略了明显的东西. 所引用的代码是否正确,对吗?

The code I'm studying is located here. I'm having trouble making sense of the fact that delete[] is used to destroy objects that are created using new. According to various readings, delete is used with new, and delete[] is used with new[]. After so long away from C++, however, I could quite easily be overlooking something obvious. Is the cited code OK, or am I right?

我在newdelete上的读数是:

  • What is difference between instantiating an object using new vs. without
  • What is difference between new and new[1]?

推荐答案

delete[]不是new[]的对应物吗?

Isn't delete[] the counterpart to new[]?

是的

delete与new一起使用,而delete []与new []一起使用

delete is used with new, and delete[] is used with new[]

正确.

delete[]虽然很花哨,但用于删除数组. new T[]总是分配一个数组,但是如果T是数组类型,则new T也可以分配一个数组.但是,这种极端情况不适用于链接的文章.这篇文章的行为不确定.

Although to be pedantic, delete[] is for deleting arrays. new T[] always allocates an array, but new T can also allocate an array if T is an array type. But this corner case does not apply to the linked article. The article has undefined behaviour.

这甚至不是文章中的错误的结尾.还有更多.例如,通过指向指向派生对象的基础子对象的Vehicle指针删除行为是不确定的,因为Vehicle的析构函数是非虚拟的.

That's not even where the bugs in the article end. There is more. For example, the behaviour deleting through a pointer to Vehicle that points to a base sub object of a derived object is undefined because the destructor of Vehicle is non-virtual.

此外,Client是可复制的,但是其复制构造函数和赋值运算符违反了析构函数有效所必需的唯一性类不变性.

Furthermore, Client is copyable, but its copy constructor and assignment operator violate the class invariant of uniqueness that is necessary for the destructor to be valid.

这篇关于`delete []`不是`new []`的对应物吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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