I tried to delete the same pointer twice, but it failed, but if I follow the same steps without making it NULL, the code works fine.
#include <iostream> struct MyClass { MyClass() {std::cout << "Allocated and Constructed" << std::endl ;} }; int main () { // allocates and constructs five objects: MyClass * p1 = new MyClass[5]; delete[] p1; delete[] p1; // The code will succeed if I comment this line of code p1=NULL; delete[] p1; delete[] p1; return 0; }
I see a good answer to the question What happens when you delete a pointer twice or more in C ++? but what makes it run, if I do it NULL, shouldn There shouldnโt be the same behavior for both cases?
You need to free only what you highlight. You highlight five instances MyClasswith new[]. So what do you need for liberation.
MyClass
new[]
. , , - .
nullptr ( NULL), . delete . ++ delete ( delete[]) .
nullptr
NULL
delete
delete[]
delete[] p1; p1. ( ++ , p1 nullptr , , , ).
delete[] p1;
p1
, delete[] p1; undefined, .
p1 = nullptr a delete[], delete . ( delete ?), .
p1 = nullptr
, 5.3.5 $2 [expr.delete] ( )
( ) delete , , (1.8), (. 10). , undefined. ( ), , new-expression. 81 , undefined.
, UB .
Source: https://habr.com/ru/post/1611551/More articles:Springfox Swagger Generates Port 80 Requests for HTTPS URLs - swaggerUse a constant in a storyboard? - iosDifference between loading a multi-page form and NSURLSession.uploadTaskWithRequest - iosCan I use the OpenStack.NET SDK with SoftLayer object storage? - openstack-swiftHow to write a virtual function in the inner class of a template class? - c ++OpenStack.Net SDK cannot access services - c #OpenStack.Net SDK cannot access a service with a region - c #Running json-server and protractor test for both Windows and Linux - javascriptAuthentication and authorization in Microservices - authenticationDoes performance impact occur when using Guava.Preconditions with concatenated strings? - javaAll Articles