c++ - If I write a placement new?How should I write normal operator delete? -
in "effective c++" item 52:write placement delete if write placement new.
meyers says widget *pw = new (std::cerr) widget;
, placement new invoked. if placement new doesn't throw exception, , delete in client code: delete pw;
. then, delete
invoke normal delete, not placement delete.
meyers comes conclusion must provide normal operator delete. so, should normal operator delete looks like? think inside of normal operator delete should resemble placement delete.
but if use normal operator new instead of placement new create object widget *pw = new widget;
, , use delete pw
afterwards, call normal operator delete wrote placement new. not seems right.
something this:
struct widget { widget() { throw std::runtime_error(""); } // custom placement new static void* operator new(std::size_t sz, const std::string& msg) { std::cout << "custom placement new called, msg = " << msg << '\n'; return ::operator new(sz); } // custom placement delete static void operator delete(void* ptr, const std::string& msg) { std::cout << "custom placement delete called, msg = " << msg << '\n'; ::operator delete(ptr); } }; int main() { try { widget* p1 = new ("widget") widget; } catch(const std::exception& e) { std::cout << e.what() << '\n'; } }
Comments
Post a Comment