You forget to add this line at the end of func()
.
delete c;
Here is the test (ideone).
c
is a raw pointer. It is not a smart pointer.
Thus, you have to delete it manually.
Deleting c
will automatically delete CONTAINER::ptr
because CONTAINER::ptr
is a unique pointer.
However, you have malloc
yourself, the more proper code might be :-
c->~_container();
Then free()
, but I don't think it is needed in this case, because CONTAINER
is not on a heap.
( I have never used malloc
, so I am not sure about this part. )
Edit:
My solution is a quick patch to solve a single problem. (not print "Destroyed")
Please also read Michael Anderson's solution.
It addresses another underlying issue of the OP's code. (malloc)
Edit2:
Here is a good link about placement new that Michael Anderson mentioned.
The code below is copied from the link (with little modification):-
int main(int argc, char* argv[]){
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
//^^^ difference : your "CONTAINER" could be char[xxxx] (without new)
A *pA = (A*)pBuffer;
for(int i = 0; i < NUMELEMENTS; ++i) {
pA[i] = new (pA + i) A();
}
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// dont forget to destroy!
for(int i = 0; i < NUMELEMENTS; ++i){
pA[i].~A();
}
delete[] pBuffer;//<--- no need to delete char[] if it is a stack variable
return 0;
}
For further detail, please see that above link (because I don't want to copy more of it to here).
Here is another useful link : Using malloc in C++ is generally not recommended.