Lecture 11 Memory Richard Gesick

advertisement
Lecture 11
Memory
Richard Gesick
Memory
•
•
•
•
There is a significant difference between value
and reference types.
Value types live within the stack space and are
accessible directly.
Reference types live in the heap and are
allocated dynamically using the "new"
command.
Primitive types like int, float, bool, etc. are
value types.
Memory
Consider the following
code:
int x, y;
Random r = new
Random();
Memory would look
like this:
Memory
Just as assignment works with value types,
assignment makes a copy of the reference
stored in one reference type and places that
copy into the other reference type.
Imagine that there are two references to the
same space in the heap as a result.
Memory
The following code:
Dog d1 = new Dog();
Dog d2;
d2 = d1;
Generates the following
memory structure:
Garbage Collection
When nothing is pointing to a space
in the heap, then the Garbage
Collector can come along and free up
that memory for some other use.
Memory Model
References can get as complicated as we'd
like. Consider the following:
Player p = new Player();
p.Position = new Vector2(100,100);
p.Weapons.Add(new Weapon("sword", new Vector(-1,-1)));
p.Weapons.Add(new Weapon("wand", new Vector(-1,-1)));
p.CurrentWeapon = p.Weapons[0]; // current weapon sword
Download