Can i use smth like the following code:
int main()
{
int* foo = new int;
double* bar = reinterpret_cast<double*>(foo);
delete bar;
}
Is it UB?
I think that we need to call operator delete only for pointers returned by operator new, but what about casting in this case?
I think that it's UB since the reinterpret_cast don't give any guarantees about the resulting pointer. Am i right?
Can somebody post the right quote from the standard, please?
§5.3.5/2 "In the first alternative (delete object), the value of
the operand of delete may be a null pointer value, a pointer to
a non-array object created by a previous new-expression, or
a pointer to a subobject (1.8) representing a base class of such
an object (Clause 10). If not, the behavior is undefined." Since
bar
points to a double
, it does not point to an object
created by a previous new-expression (which created an int
).
From 5.3.5-3:
In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
Leaving aside possible problems in using reinterpret_cast
here, this is UB because the types do not match. Imagine some nontrivial type, then you can easily see this as the "wrong" dtor would be called.
Additionally using the result of reinterpret_cast
for anything else than casting it back is mostly unspecified by the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With