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

隐身守侯 提交于 2020-06-01 05:32:03

问题


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.

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?

My readings on new and delete are:

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

回答1:


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

Yes.

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

Correct.

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.


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.

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.



来源:https://stackoverflow.com/questions/61064942/isnt-delete-the-counterpart-to-new

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