A short summary what happens when you execute:
1. a block of memory with the size
sizeof(Class)
gets allocated.
2. In this case the standard constuctor gets invoked turning the piece of memory into an instance of
Class
.
3. A pointer to the new class instance is stored in
c
.
This is what happens when you execute:
1. The destructor of
Class
get's called. This is basically what the
destroy
template above does.
2. The memory pointed to by
c
is deallocated.
The standard constructor and the destructor for an int don't do anything.
Legality:
* it should compile and do no harm in this case.
* the call to destroy should be optimized away anyway since a destructor for an int does nothing
* It should be used with care (don't use it if there is no real need), because:
1 2 3 4
|
{
Class c;
destroy(&c); // destructor of c is called here
} // destructor of c is called here again! => possibly undefined behaviour
| |
A function termplate like
destroy
is useful in low level classes like a vector.
Example:
1 2 3 4 5
|
std::vector<Class> v; //1
v.reserve(100); //2
v.push_back(Class(42)); //3
v.pop_back(); //4
v.push_back(Class(43)); //5
| |
After (1) no memory is even allocated.
After (2) memory to store at least 100 Elements has been allocated, but no constructors have been called! (remember
new Class[100]
calls the standard constructors for all 100 elements!)
After (3) the first element is now an instance of
Class
.
After (4) the last element has been destructed with a function like
destroy
but it's memory has not been released.
So, in (5) the same memory can be reused to construct another element.
To sum it up:
* Creation process is split in memory allocation (if not static or on the stack) and construction.
* Destruction process is split into calling the destructor (at end of block (stack), end of program(static), or delete when created by new) and memory deallocation.
To use only part of the creation or destruction process can be used to optimize things but is dangerous and can lead to hard to find errors.
So better don't use it ;-).