问题
I want to define my own placement new and placement delete(taking extra parameters), and I found I could invoke the placement correctly, while I couldn't access the placement delete. Could anyone tell me whether I define the placement delete incorrectly or I invoke it incorrectly?
class A
{
public:
A( int a ) : a(a){}
static void* operator new( std::size_t, int ); // the placement new
static void operator delete( void*, int )throw(); // the corresponding placement delete
private:
int a;
};
void* A::operator new( std::size_t size, int n )
{
std::cout << "size: " << size << " " << "n: " << n << std::endl;
return ::operator new(size);
}
void A::operator delete( void* p, int n )throw()
{
std::cout << "n: " << n << std::endl;
::operator delete(p);
}
int main( int argc, char* argv[] )
{
A* a = new(10) A(100);
std::cout << std::endl;
delete(4) a; // error???????????????????, but how?
return 0;
}
回答1:
Placement delete
is available only to handle exceptions which occur during evaluation of a placement new
expression. If construction finishes successfully, then later on normal delete
will be used.
You can call a placement deallocation function explicitly, but it won't have the same behavior as the delete
operator (it won't call the destructor automatically).
In your case, the corresponding code would be:
a->~A();
A::operator delete(a, 4);
Yuck!
For arrays it is even worse, because you can't retrieve the number of elements (and number of destructors to call) from the location where the compiler stored that for its own use.
Design your overloaded operator new
so that it pairs correctly with one-argument operator delete
. Then users of your class can use delete ptr;
and std::unique_ptr
etc.
If you do require custom deallocation, then an allocation wrapper which returns std::shared_ptr
with a custom deleter will be better than custom placement new.
来源:https://stackoverflow.com/questions/17656686/c-self-defined-placement-new-and-placement-delete-invoking