3-GarbageCollectionSmartPointers 1191KB Jan 14 2015 07:25

Download Report

Transcript 3-GarbageCollectionSmartPointers 1191KB Jan 14 2015 07:25

Smart Pointers
Dumb Pointers
• Pointers Necessary
– Dynamic memory
– Sharing memory
Dumb Pointers
• Pointers Necessary
– Dynamic memory
– Sharing memory
• But they are tricky
– Memory leaks
– Bad pointers
References
• References : safer pointers
– C++ :
• Non-nullable
References
• Java :
– All objects are on heap
– Stack has
• Numeric Variables
• References
– References are nullable
– Cannot delete
memory
References
• Python
• Everything is a reference… even numbers
1
x=1
x
References
• Python
• Everything is a reference… even numbers
x=1
x=2
1
x
2
References
• Python
• Everything is a reference… even numbers
x=1
x=2
y=x
1
x
2
y
References
• Python
• Everything is a reference… even numbers
x=1
x=2
y=x
x=4
1
x
2
y
4
References
• Python
• Everything is a reference… even numbers
x=1
x=2
y=x
x=4
x=x+1
1
x
2
y
4
5
Garbage Collection
• Garbage collection:
• Automatically reclaim unused memory from heap
• Various strategies
• Reference counting
• Mark and Sweep
Heap of Fish
• http://web.informatik.unibonn.de/IV/martini/Lehre/Veranstaltungen/SS00/InformatikII
/JavaSimulation/HeapOfFish.html
Compaction
• Yellow fish are garbage:
Still Problem
• Still can't make a new Red Fish
Much Better
• Compacting "live" objects reduces
fragmentation:
Smart Pointers
• C++11 brought smart pointers
– Pointers do reference counting
– Memory released when last reference is released
Shared Ptr
• shared_ptr : counts number sharing the object
– When shared_ptr leaves scope, count-– Memory deleted when count == 0
Weak Ptr
• weak_ptr : keeps track of object without
"counting"
– Can not be used directly
– Use to ask for a real shared ptr when needed
– Used to avoid cycles in shared_ptr
Unique Ptr
• unique_ptr : unshared pointer
– Can't copy can only move
– Deletes memory when pointer leaves scope
Courses With Strong/Weak
• Course Manager
responsible for
loading from DB
Courses With Strong/Weak
• Student asks for
pointers to courses
• Course manager
creates objects,
stores weak_ptr
Courses With Strong/Weak
• Student asks for
pointers to courses
• Student given
shared_ptrs
Courses With Strong/Weak
• Student asks for
pointers to courses
• Student given
shared_ptrs
Courses With Strong/Weak
• Student asks for
pointers to courses
• New student asks
for a new class
Courses With Strong/Weak
• Student asks for
pointers to courses
• New student asks
for an existing class
CS162 now has
refcount of 2
Courses With Strong/Weak
• Student asks for
pointers to courses
• First student
destroyed…
shared_ptrs with
refcount == 1
destroyed
Objective C
• Can pick:
– Manual release
– Garbage collection (on some platforms)
– ARC : Automatic Reference Counting
• Like shared_ptrs and weak_ptrs