Reputation: 20746
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?
Upvotes: 5
Views: 188
Reputation: 12413
Here you are:
5.3.5 point 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.
As for questions of what is static and dynamic type:
1.3.7 dynamic type (glvalue)
type of the most derived object (1.8) to which the glvalue denoted by a glvalue expression refers [ Example: if a pointer (8.3.1) p whose static type is “pointer to class B” is pointing to an object of class D, derived from B (Clause 10), the dynamic type of the expression *p is “D.” References (8.3.2) are treated similarly. —end example ]1.3.23 static type
type of an expression (3.9) resulting from analysis of the program without considering execution semantics [Note: The static type of an expression depends only on the form of the program in which the expression appears, and does not change while the program is executing. —end note]
Upvotes: 0
Reputation: 16046
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.
Upvotes: 2
Reputation: 153919
§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
).
Upvotes: 6