Is it correct to do the following :
MyClass mc1(1, 1);
MyClass* pmc1 = &mc1;
delete pmc1;
I saw it in a code example. I thought we can call delete on pointers to object that is allocated on the heap but this pointer points to an object on the stack, isn't it ? Could someone explain it.
No. You should never call delete
on a pointer to the object that hasn't been created using new
. It is undefined behavior.
C++ Standard n3337 § 5.3.5/2 Delete
(...)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.