Friday, February 27, 2009

C++ Memory Management

C++ Memory Management - From Fear to Triumph
1. Alternatives have automated memory management. Python has reference-counted model, and Java has sophisticated garbage collector.
2. Memory errors come in two basic types: the dangling reference and the memory leak.
3. The hidden memory allocation inside classes is a side effect, we need consider available alternatives.
[1] Allow the user to supply her own buffer (e.g., as a parameter to the constructor)
[2] Use a member object instead of a pointer to a dynamically allocated object.
[3] Strictly local objects that are used only for the duration of a method call should be declared as automatic variables.
[4] Use an allocator object to get the memory, and allow the user to specify his owner allocator.
4. Techniques for C++ Memory Management
5. Return value optimization.
SimpleString return_by_value() {
// Constructing the return value helps to eliminate the temporary objects associated with return-by-value
return SimpleString("ReturnValueOptimization");
}

From: http://www.linuxdevcenter.com/pub/a/linux/2003/05/08/cpp_mm-1.html?page=1

Difference between malloc/free and new/delete
[1] malloc() allocates a bunch of bytes while 'new' does the allocation as well as the responsibility of calling the constructor.
[2] malloc() returns 'NULL' on failure while 'new' throws an exception object of type 'std::bad_alloc'.
[3] 'free()' on 'NULL' pointers is not safe while 'delete' is.

No comments: