user1071777
user1071777

Reputation: 1307

deleting a char array with cast to char*?

Which of these should be used?

char *ex = new char[255];
// code
delete [] ex;

or

char *ex = new char[255];
// code
delete [] (char *) ex;

I'm thinking that the cast isn't necessary, but would it have any effect on the actual deletion?

Upvotes: 2

Views: 334

Answers (3)

bert-jan
bert-jan

Reputation: 968

delete[] destroys (or destructs) a number of objects and then frees the memory. If the type is not an object, it simply frees the memory without calling destructors. This would be good:

 class some_class
 {
       some_class(int);
 };

 ....
 some_class *p = new some_class[[2]](0)(1);

 delete[] p; // delete calculates how many objects where created, and call destructors of all objects, then frees the memory (which is twice sizeof(some_class)

Upvotes: 0

Alok Save
Alok Save

Reputation: 206518

char *ex = new char[255];
// code
delete [] ex;

You do not need to cast, The cast won't have any effect anyways.

The C++ Standard does not need you to do any casting. Here is the reference.

Section §3.7.3.2.3:

The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](size_t) or operator new[](size_t, const std::nothrow_t&) in the standard library.

Upvotes: 4

hmjd
hmjd

Reputation: 121961

It is not necessary and would have no effect. You are casting a char* to a char*.

Upvotes: 4

Related Questions