Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use delete to destroy objects in C++

Shulou Source: shulou.com Published: 2022-06-02 05:57:02 09月19日 Update

This article is to share with you about how to use delete in C++ to destroy objects. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Reason (reason)

That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.

This is the requirement of C++ language, if you use it incorrectly, it will lead to resource release error or memory corruption.

Example, bad (negative example)

Void f (int n)

{

Auto p = new X [n]; / / n default constructed Xs

/ /...

Delete p; / / error: just delete the object p, rather than delete the array p []

} Note (note)

This example not only violates the no naked new rule as in the previous example, it has many more problems.

The sample code not only violates the new rule that forbids exposure in the previous example, but there are many other errors.

Enforcement (implementation recommendations)

If the new and the delete are in the same scope, mistakes can be flagged.

If new and delete belong to the same scope, the error can be marked.

If the new and the delete are in a constructor/destructor pair, mistakes can be flagged.

If new and delete are in the constructor and destructor respectively, the error can be marked.

The above is how to use delete in C++ to destroy objects. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Errors caching more examples objects functions tags knowledge articles utility code functions memory reasons on the contrary that is work sessions suggestions articles read Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia macOS Docker Xiaomi vpn