Reputation: 593
Just wondering since I am working with a partner on a C++ project, is it possible to explicitly delete an object that has been initialized on the stack? (so without pointer)
For example:
MinHeap h(data); // on stack
Vs
MinHeap *h = new MinHeap();
This has never come up before since I always allocated memory on the heap for an large object.
Upvotes: 3
Views: 2273
Reputation: 15164
A stack variable is always valid in its current scope. You can enforce the scope (and thus freeing the allocated memory) by using curly brackets around the block you want to have the instance valid in:
{
MinHeap h(data);
// Do stuff here
} // h gets freed here
Upvotes: 12
Reputation: 126562
is it possible to explicitly delete an object that has been initialized on the stack?
No, it is not possible.
According to Paragraph 5.3.5/2 of the C++11 Standard on delete
expressions:
If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. 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. [...]
Also relevant is Paragraph 3.7.3/3 about variables with automatic storage duration (i.e. allocated "on the stack"):
If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.
Upvotes: 2
Reputation: 409482
Short and only answer would be no.
If an object is allocated on the stack it's not actually you that allocates it but the compiler that does it for you. It's also the compilers to responsibility to "unallocate" (or "delete") the object when the scope of the function ends.
The only reason to use delete
is to deallocate something you allocated with new
.
Upvotes: 3