Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.

Similar presentations


Presentation on theme: "CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones."— Presentation transcript:

1 CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones in C++ Copy constructor trick for assignment –Ensures release of existing resource and acquisition of the new resource both succeed or fail together RAII (a.k.a. Guard) –ties dynamic resources to other (esp. automatic) scopes Reference counting –ties dynamic lifetime to a group of references Copy-on-write –allows more efficient management of multiple aliasing

2 CSE 332: C++ memory management idioms Copy Constructor Trick for Assignment Cleanup/assignment succeed or fail together class Array { public: Array(unsigned int) ; Array(const Array &); // assume copy constructor makes a deep copy ~Array(); Array & operator=(const Array &a); private: int * ints_; size_t size_; }; Array & Array::operator=(const Array &a) { if (&a != this) { Array temp(a); std::swap(temp.ints_, ints_); std::swap(temp.size_, size_); } return *this; }

3 CSE 332: C++ memory management idioms Resource Acquisition Is Initialization (RAII)‏ Also referred to as the “Guard Idiom” –However, the term “RAII” is more widely used in C++ Relies on the fact that in C++ a stack object’s destructor is called when stack frame pops Idea: we can use a stack object to hold the ownership of a heap object, or any other resource that requires explicit clean up –Initialize stack object when the resource is allocated –De-allocate resource in the stack object’s destructor

4 CSE 332: C++ memory management idioms Example: C++ auto_ptr Class Template RAII idiom example C++ has an auto_ptr class template #include using namespace std; auto_ptr assumes ownership of aliased X auto_ptr destructor calls delete on the pointer to the owned X Call release to break ownership by auto_ptr when it’s safe to do so Combines well with other memory idioms Foo *createAndInit() { Foo *f = new Foo; auto_ptr p(f); init(f);// may throw exception p.release(); return f; } int run () { try { Foo *d = createAndInit(); } catch (...) { }

5 CSE 332: C++ memory management idioms More About auto_ptr and RAII auto_ptr copy constructor transfers ownership from the older to the newer one –E.g., if you pass an auto_ptr by value to a function –E.g., if you return an auto_ptr by value as a function result Ownership is passed along a chain of calls Makes sure it’s cleaned up where chain ends auto_ptr createAndInit() { auto_ptr p(new Foo); p = init(p); // may throw exception return p; } int run () { try { auto_ptr q(createAndInit()); // do something with object return 0; } catch (...) { return 1; }

6 CSE 332: C++ memory management idioms Introduction to Reference Counting Basic Problem –Resource sharing is often more efficient than copying –But it’s hard to tell when all are done using a resource –Must avoid early deletion –Must avoid leaks Solution Approach –Share both the resource and also a counter –Each new reference increments the counter –When a reference is done, it decrements the counter –When count drops to zero, delete resource and counter –“last one out shuts off the lights” Resource counter == 3 reference

7 CSE 332: C++ memory management idioms Introduction to Copy on Write Basic Problem –Reference counting enables safe and efficient sharing –But what if modifications are made to the resource? –May want logically separate copies of resource Solution –Start with reference counting –Writer checks for count > 1 Copies reference & counter Updates both counters Performs the write –Readers all share a copy, each writer can get its own Resource counter == 2 reference Resource 2 counter == 1 write()

8 CSE 332: C++ memory management idioms Caution: Containers and Smart Pointers STL containers pose a special problem –Keep contents by value, assign and copy at will –Behavior of auto_ptrs works fine in functions … –… but won’t work within a vector (risks a crash!) How to use smart pointers in containers? –Need a better suited type of smart pointer –Can write one that does reference counting –Other good ideas are found in the boost library

9 CSE 332: C++ memory management idioms Summary: Memory Management Tips Know what goes where in memory Understand mechanics of stack and heap allocation Watch for simple (and complex) lifetime errors Think about shallow copy vs. deep copy (problems and performance trade-offs) Master useful idioms for C++ memory management –Learn how they work –Understand when to apply them –Look for ways to apply them in the labs and beyond


Download ppt "CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones."

Similar presentations


Ads by Google