Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
delete[] p or delete[] *p
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
Reply to thread
Message
[QUOTE="Paul, post: 4198371"] Why are they UB? After having a read through the rellevant pages of the standard I don't think that it is UB. The standard specifically states that the pointer returned from new must be castable. Consider this more complex example: class Base{ public: Base() {std::cout<<"Constructing base\n";} virtual ~Base(){std::cout<<"Destructing base\n";} }; class Derived: public Base{ public: Derived() {std::cout<<"Constructing derived\n";} ~Derived(){std::cout<<"Destructing derived\n";} }; int main() { Base (*p2)[3] = (Base (*)[3])new Derived[2][3]; delete[] p2; } The cast is required , otherwise you'd need to loop through the array columns for allocation and deallocation.. I could cast it back prior to deletion with: delete[] (Derived (*)[3])p2; But this is unneccessary because Base type is an acceptable pointer type. The type is only neccessay for the correct destruction of objects. For example: Base *p2 = new Derived[3]; delete[] p2; is identical to Base (*p2)[3] = (Base (*)[3])new Derived[3]; deletep[] p2; The type that is relevant here is that it is Base or Derived, the number of elements destructed is decided by the C runtime. As long as the dereferenced pointer passed to delete has the same value as the pointer returned by new all is ok, because it is converted to void* anyway. The C runtime decides whether it deletes 3 objects or 1 , not the type system. If int[3] and int* both point to the same address, then converted to void* they are identical. The C++ type system is only interested in if its an array of int-typ, Derived-type , or Base-type, It not up to the type system to deicde how many destructors to call. It would be UB if you converted the pointer to a different type altogether for example: double* p = (double*)new int[6]; delete[] p; This would be UB , because you are converting to a new type of array.. Ok I see you are talking about implicit pointer conversion. HTH Paul. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
delete[] p or delete[] *p
Top