Re: Why no placement delete?
Andy Venikov wrote:
What's the rational for not having placement delete?
I know you can define your own placement operator delete, but it will
only be called in case a constructor throws an exception when placement
new is called. You can't call placement delete directly.
This limitation greatly impairs the use of custom allocators.
For example, if you want you allocations to come from a specific memory
region and you have a handle to that region you can: (assuming
regionAllocator is an object of a custom RegionAllocator class)
X * px = new (regionAllocator) X;
But you can't
delete (regionAllocator) px;
you can only
delete px;
That puts an unduly difficult requirement on (presumably custom)
operator delete to figure out where the memory came from. And no, it's
not always possible to embed that information with the returned memory.
The only rational I can think of is the ability to destroy any object by
just having a pointer to it, which would make generic destructors a bit
easy. But in my view this is a draconian requirement.
Thanks,
Andy.
I hope I'm not missing the point of your question here, but can't you
just do:
px->~X()
?
I don't use placement new all that often, but off the top of my head I
seem to remember the idea being something like this:
#include <memory>
#include <string>
int main()
{
using std::string;
void *mem = ::operator new(sizeof(string));
string *s = new (mem) string;
*s = "Wibble";
s->~string();
::operator delete(mem);
return 0;
}
In other words, the explicit destructor call destroys the string
constructed by placement new. So you have to know that your string was
allocated by placement new, sure, but this isn't really any different
from having to know that your pointer points to an array rather than a
single object (which also changes the syntax at the point of destruction
- from delete to delete[]).
Or are you asking something more subtle?
Best wishes,
Stu
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]