Fizzbuzz TDD Code Review, Makefiles Part II, Smart Pointers
Today I was going to go into more detail on Hash Tables, but Portnoff wanted me to look at his code, so we did a code review for the first half of class. I took at a look at his functions and his Makefile, and tweaked them a little bit so that they were more in line philosophically with what I like to see.
We then talked a bit about the new assignment (Hash Tables) in which you will have to write a hash table with three different implementations. It's a backdoor way of explaining how inheritance works, and we'll get to a full lecture on it later.
Smart pointers (unique_ptr and shared_ptr) are two very nice alternatives to using raw pointers with new and delete. Tracking when and where raw pointers have to be deleted can be very hard if you are sort of allocating and deallocating them willy-nilly, and raw pointers don't tell you if you're pointing at one object or an array of objects, and if it's an array how big the array is. Worse, it doesn't tell you who "owns" a pointer, meaning who is responsible for cleaning it up (deleting it) when you're done with it.
Unique_ptr solves all those problems by basically making it very easy to new memory (without actually calling new, call make_unique() instead) and it automatically frees memory when it is not in scope any more, and can't be copied without moving (transferring ownership with move()) to another function, at which point that function owns the pointer. Nice!
Shared_ptr are for those times when you want there to be copies of the pointer. It's a bit slower than unique_ptr, but not that bad, but it's a mistake to always use shared_ptr just because you want to copy it. You should use the right pointer for your needs. If multiple people all need to have the same pointer to something? Shared pointer it is! But try making it work with unique_ptr first if this isn't your use scenario.