
Dynamic Memory Management in C++: Smart Pointers and Memory Allocation
Learn about dynamic memory management in C++ using smart pointers to prevent memory leaks. Understand the use of unique_ptr, shared_ptr, and weak_ptr for safe memory allocation. Avoid direct use of new and delete for better memory management.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
E81 CSE 428S: Multi-Paradigm Programming in C++ Dynamic Memory Management Department of Computer Science & Engineering Washington University, St. Louis MO Chris Gill and Oren Bell {cdgill, oren.bell}@wustl.edu 1
Dynamic Memory and Smart Pointers Raw memory allocation uses malloc and free (or new and delete) Developer can lose track of pointers, leading to unfreed pointers and memory leaks Prefer to use safe memory allocation templates E.g., the make_shared function template Does a lot of error checking for you (allocation can fail!) Prefer to use smart pointers to dynamic memory E.g., the shared_ptr class template is often what you want Does reference counting and other useful things for you (ensures safe deallocation along all code paths!) Copy and assignment semantics for shared_ptr Each shared_ptr maintains a reference count, for how many shared_ptr aliases there are to a chunk of dynamic memory Copy construction, assignment, and destruction of a shared_ptr modifies reference count CSE 428S Multi-Paradigm Programming in C++ 2
unique_ptr and weak_ptr The unique_ptr template can be used for direct ownership of a dynamically allocated object Its destructor destroys the object and deallocates the memory Copy construction and copy assignment of unique_ptr are not allowed, but move construction and move assignment are (stay tuned for more about those issues next time) That lets us move unique_ptr aliases up and down call stack The weak_ptr template can be used for aliases that don t participate in shared_ptr reference counting Must lock weak_ptr to make sure what it aliases still exists If so, then it s safe to access the aliased object CSE 428S Multi-Paradigm Programming in C++ 3
Using new and delete Directly Generally not recommended if there s a way to use safe allocation functions and smart pointers instead There is a lot to manage, including handling failures and ensuring deallocation along all possible code paths That said, it s good to know how they work Especially since you may want to dig into library code that uses them, in order to understand how it works Especially since a fair amount of legacy code someone else may have written uses them Use new to initialize (rather than to assign) pointers Prefer to do that where the pointer is declared, if possible Make sure that delete is used safely, exactly once Don t delete an object that code may still try to access Make sure the object is deleted after all possible accesses Make sure the object isn t deleted more than once CSE 428S Multi-Paradigm Programming in C++ 4
Using new and delete Directly Every new must have a corresponding delete { // Bad int x; int *ptr = &x; delete ptr; } { } // Acceptable Type* ptr = new Type(); delete ptr; Call delete only once { // Bad Type* ptr = new Type(); delete ptr; delete ptr; } Don t reassign initialized pointers { // Bad Type* ptr = new Type(); ptr = new Type(); } CSE 428S Multi-Paradigm Programming in C++ 5
Special Forms of Allocation/Deallocation E.g., string * strarray = new string [10]; allocates enough memory, ensures constructor called at each position E.g., delete [] strarray; ensures destructor called at each position, then deallocates the memory Decoupling memory allocation and object initialization Allocators allocate memory (but don t call constructors in it) Then, can repeatedly construct objects in place, either via the allocator s construct method or by using placement new Or, can use algorithms to copy (invokes copy constructors) or fill (invokes default constructors) the uninitialized memory Decoupling destruction and deallocation To reverse in-place construction, call destructors explicitly This can be done via the allocator s member function Then, can use the allocator again to deallocate the memory CSE 428S Multi-Paradigm Programming in C++ 6
Studio 10 Use make_shared and shared_ptr (and weak_ptr with lock()) to manage dynamic objects safely Pass a dynamic object up/down call stack via unique_ptr Use various forms of new, delete, allocators, and explicit destructors to manage dynamic memory, and explore some of the potential pitfalls of that Studios 0 through 11 are due 11:59pm Monday October 16th (the night before Exam 0) Submit as soon as each is done so you get feedback and can resubmit any that may be marked incomplete CSE 428S Multi-Paradigm Programming in C++ 7