# Customizing new and delete, Notes(8), Effective C++

## Customizing new and delete

(I read a Chinese version of the book, any translation problem plz point out.

### Understand the behavior of the new-handler

well-designed new-handler should do:

• make more memory to be used, i.e., more likely to let the next operator new be successful.
• install another new-handler, i.e., let operator new call set_new_handler.
• uninstall new-handler, i.e., pass nullptr to operator new.
• throw bad_alloc (or derived from bad_alloc) error.
• no return (usually call abort or exit).

implement the new_handler of class:

reuse the code above due to the same implementation for different classes:

nothrow new:
it is limited, only adapted to memory allocated, and intermediate constructor called may throw exception.

### Understand when it makes sense to replace new and delete

• to check the wrong usage.
• to improve the efficiency of allocation and deallocation.
• to collect the log of usage.
• to decrease the additional space cost caused by default memory manager.
• to improve the suboptimal alignment.
• to make related objects clustered.

### Adhere to convention when writing new and delete

• operator new should have an infinite loop which tries to allocate memory.
• operator delete should do nothing when passed by nullptr, “Class version” should
handle the “wrong apply that requires the bigger size than the true size”.

### Write placement delete if you write placement new

• when write Widget* pw = new Widget;, two functions are called, one is operator new, one is Widget’s default construtor.
if the constructor throws, the memory allocated by the first one should be recovered, or it will be memory leak.
so the corresponding operator delete should be provided correctly.
• when write a placement operator new, plz be sure to write a placement operator delete.
• when declaring placement new and placement delete, plz do not hide the normal version intendedly or unconsciously.

1. 除非注明，本博文即为原创，转载请注明链接地址
2. 本博文只代表博主当时的观点或结论，请不要恶意攻击
3. 如果本文帮到了您，不妨点一下 下面分享到 按钮，让更多的人看到