|
Boost : |
From: Ehsan Akhgari (ehsan_at_[hidden])
Date: 2003-10-13 13:45:17
[snip]
> 1. Can the same paired placement delete be be used for destruction
> after the object is created:
>
> T* t = ....
> t->~T();
> T::operator delete(t);
Yes:
#include <new>
#include <iostream>
struct X
{
X() { std::cout << "X()\n"; }
~X() { std::cout << "~X()\n"; }
};
int main()
{
void * pv = operator new( sizeof(X) ); // allocate
X * p = new( pv ) X; // create
delete( pv, p ); // destroy
operator delete( p ); // deallocate
}
Of course you can call the dtor explicitly (as you have done in your
example.)
To figure this out, separate the allocation/deallocation phase with the
creation/destruction phase. The allocation/deallocation phase should
use the same method (i.e. using ::operator new( ) and ::operator delete(
), std::malloc( ) and std::free( ), etc.). The creation/destruction
should also pair up: if you use placement new, you should use placement
delete as well (which doesn't free the memory.) The way I have shown in
my code, if X defines its own version of placement new and delete, they
will get called, instead of the default global ones provided in <new>.
> 2. Is the issue that if object is created in raw memory via placement
> new, then if it's deleted by a program, the raw memory is never freed?
>
> T* t = ..... // does new(pt) T, where 'pt' could point to
> anything.
> delete t; // does nothing, causing memory leak if 'pt'
> was dynamically
> // allocated.
Yes, if you use placement delete. This makes sense, for example, when
the memory is not allocated using ::operator new( ), or when the
class-specific operator delete is provided. Any approach other than
this leads to disaster. The following code, for example, is the correct
way to free the memory allocated using a custom allocator:
int main()
{
void * pv = custom_alloc( sizeof(X) ); // allocate
X * p = new( pv ) X; // create
delete( pv, p ); // destroy
custom_dealloc( p ); // deallocate
}
HTH,
-------------
Ehsan Akhgari
List Owner: MSVC_at_[hidden]
[ Email: ehsan_at_[hidden] ]
[ WWW: http://www.beginthread.com/Ehsan ]
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk