c++ self-defined placement new and placement delete invoking

妖精的绣舞 提交于 2020-01-03 02:27:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!