[content]
Item 49: Understand the behavior of the new-handler
DO: When operator new is unable to fulfill a memory request, it calls the new-handler function repeatedly until it can find enough memory. A well designed new handler function must do one of the following things:
1. Make more memory available.
2. Install a different new handler.
3. Deinstall the new handler.
4. Throw an exception.
5. Not return.
Item 50: Understand when it makes sense to replace new and delete
DO: There are valid situations where we want to replace new and delete.
1. To detect usage errors.
2. To increase the speed of allocation and deallocation.
3. To reduce the space overhead of default memory management.
4. To compensate for suboptimal alignment in the default allocator.
5. To cluster related objects to each other.
6. To obtain unconventional behavior.
Item 51: Adhere to convention when writing new and delete
DO: new operator needs to do following things:
1. Contain an infinite loop to allocate memory
2. Call new-handler, when it cannot fulfill the memory request
3. Handle request for zero byte
4. Handle requests for more bytes than the current class’s size. (This could happen when derived class delegates its new operator to base class)
DO: delete operator needs to align with new operator. If the new operator is called to allocate a different size of memory, delete needs to be called with the same size.
Item 52: Write placement delete if you write placement new
When an operator new function takes extra parameters (other than the mandatory size_t argument), that function is known as a placement version of new.
DO: Placement delete is called only if an exception arises from a constructor call that’s coupled to a placement new. Therefore, if you define placement new, you must also define placement delete.
DO: When defining placement new operator, also define normal new operator. Otherwise, the name could be hidden.
class Base {
public:
static void* operator new(std::size_t size, std::ostream& log_stream) throw(std::bad_alloc);
};
Base *pb = new Base; // error! The normal form of operator new is hidden