Presentation is loading. Please wait.

Presentation is loading. Please wait.

Making Dynamic Memory Allocation Safer

Similar presentations


Presentation on theme: "Making Dynamic Memory Allocation Safer"— Presentation transcript:

1 Making Dynamic Memory Allocation Safer
Smart Pointers Making Dynamic Memory Allocation Safer

2 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)

3 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

4 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 may copy, assign, pass by value may reassign, check if assigned, compare, use in STL deallocating calls destructor when last reference disappears (gets reassigned, goes out of scope)

5 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)


Download ppt "Making Dynamic Memory Allocation Safer"

Similar presentations


Ads by Google