How does C++ free the memory when a constructor throws an exception and a custom new is used

前端 未结 5 1146
春和景丽
春和景丽 2021-02-19 16:07

I see the following constructs:

  • new X will free the memory if X constructor throws.

  • operator new() can be

5条回答
  •  旧时难觅i
    2021-02-19 16:36

    When the construction of the object being constructed as a part of the new-expression fails, a corresponding deallocation function -- if there is one -- will be called. For instance

    new X;
    

    will use the following pair of allocation/deallocation functions.

    void * operator new(std::size_t);
    void operator delete(void *);
    

    Similarly, for a placement new of the form

    new(&a) X;
    

    the placement versions of operator new and operator delete function will be used.

    void * operator new(std::size_t, void *);
    void operator delete(void *, void *);
    

    Note that the last function intentionally performs no action.

提交回复
热议问题