110 likes | 148 Views
Understand the benefits of smart pointers in C++ for safer dynamic memory allocation. Learn the pitfalls of raw pointers, the advantages of unique_ptr and shared_ptr, along with best practices for managing memory efficiently. Dive into examples and comparisons to improve your programming skills.
E N D
Smart Pointers Making Dynamic Memory Allocation Safer
What’s Wrong with Dumb (Raw) Pointers • ownership unclear: declaration does not state whether it should be destroyed when done using • unclear if points to scalar or array • exactly once destruction is problematic: what if there are paths in program where pointer is not deallocated (memory leak) or doubly deallocated (unspecified behavior) • exceptions are particularly known for escaping clear deallocation paths • unclear if loose (dangles)
unique_ptr • ensures there is a single pointer to dynamically allocated object, invokes destructor when goes out of scope • need <memory> • declaring unique_ptr<Myclass> p1(new Myclass(1)); // C++11 auto p2 = make_unique<Myclass>(1); // C++14 • using • dereference and arrow operator are supported • cannot copy, assign, pass by value • can std::move() p2 = std::move(p1); unique_ptr<Myclass> p3(std::move(p1)); • can reassign: p1.reset(); p2.reset(new Myclass(1)); p3=nullptr; • can check if assigned: if(p1) …., can compare • can be used in STL (no copying algs.): std::vector<unique_ptr<int>> v; • deallocating: destructor is called on owned object if • pointer goes out of scope • pointer gets reassigned • pointer is assigned nullptr
Managing Arrays with unique_ptr • unique_ptrmay manage arrays • syntax: unique_ptr<int[]> = a(new int[5]); • indexing allowed: a[4] = 44; • no range checking, out-of-range error possible • unique pointer manages the whole array: proper deallocation on reassignment and going out of scope • pointer arithmetic not allowed
shared_ptr • keeps number of pointers pointing to object, deallocates when zero • need <memory> • declaring auto sp = std::make_shared<Myclass>(10); // C++11 • using • dereference and arrow operators supported • may copy, assign, pass by value • may reassign, check if assigned, compare, use in STL • can check how many references sp.use_count() • deallocating • calls destructor when last reference disappears (gets reassigned, goes out of scope)
Miscelany • no naked new and delete: cause problems: int *p = new int(55); unique_ptr<int> p1 (p); unique_ptr<int> p2 (p); • preferably no new/delete at all (possible for C++14) • shared_ptr is more powerful but less efficient than unique_ptr • unique_ptr is just a wrapper over raw pointer • shared_ptr stores reference count, requires two memory lookups • auto_ptr is depreciated and to be avoided • shared_ptr may have a reference cycle that prevents objects from de-allocation. weak_ptr is not included in reference count, may be loose (dangle)