Smart Pointers - PowerPoint PPT Presentation

Loading...

PPT – Smart Pointers PowerPoint presentation | free to download - id: 17b645-ZDc1Z



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

Smart Pointers

Description:

Dumb Pointers. Suppose T is a class. T* is a 'dumb pointer' ... allows to access the dumb pointer version of an auto_ptr. PLAB. Strategy #4: Reference Counting ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 35
Provided by: csHu
Learn more at: http://www.cs.huji.ac.il
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: Smart Pointers


1
Smart Pointers
2
Memory Management
  • One of the major issues in writing C/C code is
    managing dynamically allocated memory
  • Biggest question is how to ensure that allocated
    memory will be freed when it is no longer in use

3
Strategy 1 Fixed Ownership
  • Allocated pointer belongs to the entity (function
    or objects) that created it
  • That entity is responsible for freeing the
    pointer
  • void foo()
  • char mem new char1000
  • delete mem

4
Example String class
  • class String
  • public
  • String( char const str )
  • int l strlen(str)
  • m_data new charl
  • memcpy(m_data, str, l)
  • String()
  • delete m_data
  • private
  • char m_data
  • The memory for char represented by String is
    owned by the object
  • Class encapsulates details of memory management
  • With careful implementation, this class is
    memory-tight

5
Strategy 2 Dynamic ownership (compile time)
  • Object has an owner
  • However, owner changes through specific function
    calls
  • Example
  • strdup(s) allocates new memory and transfers it
    with return value
  • strdup does not release the memory

6
Ownership transfer and interface design
  • Design principle
  • keep free resources at the same level you
    allocate them
  • Reduces memory leaks due to interface problems

7
Example design choices
  • ReadLine read a line of input
  • char ReadLine() returns pointer to newly
    allocated memory user has to free it
  • char ReadLine() returns pointer to static
    buffer user has to copy line to another buffer
  • void ReadLine(char Buffer) uses a user
    supplied buffer ReadLine cannot resize buffer

8
Strategy 3 Dynamic ownership (run time)
  • In some case we cannot know who will own a
    pointer
  • In other cases, we do not want the programmer to
    remember who owns what
  • Can we use an object that remembers who owns
    the object?

9
Dumb Pointers
  • Suppose T is a class
  • T is a dumb pointer supplied by compiler
  • It remembers the address of the object and allows
    us to access it, but nothing else
  • Can we build smarter pointers?

10
The Pointer Interface
  • To implement a pointer-like object we need
  • pointerpointer( T)
  • pointerpointer( pointer const )
  • pointer operator( pointer const )
  • T pointeroperator()
  • T const pointeroperator() const
  • T pointeroperator-gt()
  • T const pointeroperator-gt() const
  • pointeroperator void const() const

11
Pointer class
  • templatelt class Tgt class pointer
  • public
  • pointer( T p NULL )
  • m_ptr(p)
  • T operator()
  • return m_ptr
  • private
  • T m_ptr

12
Smart Pointers
  • We can ensure that pointer cleans up after
    itself
  • Simply add destructor
  • pointerpointer()
  • if( m_ptr ! NULL )
  • delete m_ptr
  • This class is called auto_ptr

13
Auto_ptr
  • struct bar
  • void foo()
  • auto_ptrltbargt myBar new bar
  • // use myBar as a pointer
  • // myBar is deleted automatically

14
Auto_ptr in exceptions
  • Auto_ptrs provide clean mechanism to deal with
    exception
  • void foo()
  • auto_ptrltbargt myBar new bar
  • apple() // apple might throw an execption
  • // myBar is deleted automatically
  • // even if an exception is thrown by apple

15
Auto_ptr
  • auto_ptr is like a pointer, but not exactly
  • void foo()
  • auto_ptrltbargt myBar new bar
  • if( )
  • auto_ptrltbargt myOtherBar myBar
  • What happens in this example?

16
Transfer of Ownership
  • To avoid multiple deletes, auto_ptr ensures that
    only one auto_ptr points to a certain object
  • The statement
  • auto_ptrltbargt myOtherBar myBar
  • transfer the ownership from myBar to myOtherBar
  • How do we achieve this?

17
auto_ptr details
  • auto_ptr( auto_ptr rhs )
  • m_ptr( rhs.release() )
  • auto_ptr operator( auto_ptr rhs )
  • reset( rhs.release() )
  • return this
  • void reset(T p NULL)
  • if( m_ptr ! p ) delete m_ptr
  • m_ptr p
  • T release()
  • T tmp m_ptr
  • m_ptr NULL
  • return tmp

18
Auto_ptr summary
  • Provide mechanism for transfer of ownerships
  • Can be dangerous
  • Requires discipline from programmer
  • Does not replace the need for pointers
  • The method T auto_ptrltTgtget() allows to
    access the dumb pointer version of an auto_ptr

19
Strategy 4 Reference Counting
  • In some cases, we do not want to establish
    ownership
  • Managing ownership within forces us to make
    unnecessary copies
  • Can we get away with memory management without
    authorship?
  • The general mechanism of reference counting
    provides one solution

20
Reference Counting
  • String a foo bar
  • String b a
  • String c a
  • The resulting memory structure

stack
heap
21
Reference counting
  • Can we do better?
  • Idea Do not copy value of string
  • Have all object point to the same memory
  • How do we know when to free the memory?

22
Reference Counting
  • Solution
  • Store a reference counter that counts number of
    pointers
  • Reference counter shows whether the object is in
    use

a
b
c
23
Reference Counting
1
After Object Creation
24
String with reference counting
  • See String.h

25
Example revisited
  • Returning to the ReadLine example
  • String ReadLine()
  • returns a String object
  • A new String is copied on return value
  • But the actual memory is not copied
  • Ownership transfer occur smoothly with minimal
    overhead

26
ReadLine Example
  • String ReadLine()
  • String line
  • // do read
  • return line
  • void foo()
  • String a ReadLine()

27
General Purpose Reference Counting
  • See RCPointer.h

28
Reference Counting
  • Suppose String has operator
  • Consider the following code
  • String a foo bar
  • String b a
  • String c a
  • c2 l
  • What does this code do?

29
Reference Counting
  • After we modify c, it is no longer identical to a
    and b
  • We can no longer save memory by storing all three
    strings in one place
  • Solution
  • Clone on Write make a copy of an object when
    it is modified

30
Implementing operator in String
  • Read-only access
  • char const operator(int i) const
  • return m_ptr-gtm_datai
  • Read/Write access
  • char operator(int i)
  • if( m_ptr-gtm_rc gt 1 )
  • // make a new copy of the string
  • m_ptr-gtm_rc--
  • m_ptr new StringValue( m_ptr )
  • return m_ptr-gtm_datai

31
Clone on Write
  • Perform the copy operation only when new copy is
    needed
  • This is an instance of lazy evaluation
  • How can we perform this in a generic RCPointer?

32
Template Clone on Write
  • Distinguish between
  • read only access
  • T const RCPointerltTgtoperator() const
  • T const RCPointerltTgtoperator-gt() const
  • and read/write access
  • T RCPointerltTgtoperator()
  • T RCPointerltTgtoperator-gt()
  • In these operations we perform copy

33
Reference counting and cycles
  • Reference counting could have been used as an
    automatic garbage collection in C.
  • Problem Data structures can include cycles. In
    this case the pointers will never be deleted.

If all these pointers were reference counted,
then no memory would be freed
34
When to use what ?
  • auto_ptr/Ownership transfer
  • simple yet problematic. Good for local variables
  • Reference counting
  • Simple, memory safe, efficient, problematic when
    modifying the object.
  • Very good for large objects, and STL containers
    providing these do not change the objects.
  • Reference counting with Clone On Write
  • Optimal for STL, and for large objects.
    problematic for data structures with cycles.
About PowerShow.com