c++ - Calling of delete after construction throwing an exception -
i'm reading effective c++ 3rd edition, item52 "write placement delete if write placement new".
i want how make operator delete automatically called after construction throwing exception.
#include <iostream> using namespace std; class { int i; public: static void* operator new(std::size_t size) throw(std::bad_alloc) { return malloc(size); } static void operator delete(void* p) throw() { cout << "delete" << endl; free(p); } a() { throw exception(); } }; int main() { a* = new a; }
the above codes output:
terminate called after throwing instance of 'std::exception' what(): std::exception [1] 28476 abort ./test_clion
reference: operator delete, operator delete[]
i should write new
in try {}
. know little exceptions now.
#include <iostream> using namespace std; class { int i; public: static void* operator new(std::size_t size) throw(std::bad_alloc) { return malloc(size); } static void operator delete(void* p) throw() { cout << "delete" << endl; free(p); } a() { throw exception(); } }; int main() { try { a* = new a; } catch (const exception&) { } }
and output:
delete
Comments
Post a Comment