Thursday, 22 October 2015

Low-Level Programming_Post5

Low-Level Programming: Post 5 22/10/2015

October 22nd 2015 is the date of the fifth lesson on Low-Level Programming.

In today's lesson, we began with the traditional overview of what we were going to learn today, with the first point a review of what we learnt last week (Static and Dynamic Casting). However, before we began the slides, we were tasked to 'peer review' other people's blogs. However, my table only viewed one out of the four dev blogs, as we started discussing about 'Cache Coherency'.

After reviewing the blog, we were given the official marking and expectations for the module. 75% of the marks go towards the portfolio (Portfolio of tasks and Assignments/Practical Work) and 25% of the marks go towards the dev blogs (Tracking of Learning and that the dev blogs are completed on a daily basis).

The following points are what we learnt in the lesson...

  • Memory: Automagic Pointers, Deep Copies, Virtual Destructors.
  • Containers: Structs and Vector.
  • Libraries: Practical Work involving the use of a third-party library.
Similar to last week, I will not be going over what we reviewed (as that is on last week's post). Therefore, I will be starting with Memory.

Memory Management/Class Cleanup
  • Class Memory: When we create classes, there's a good chance it's going to store some sort of data regarding it's state.
  • Inheritance: When we use inheritance, we should ensure our destructor is virtual to make sure all the respective destructors in the hierarchy are called.
  • Dynamic Memory: If we've used the new keyword to store data, we've got chunks of memory on the heap that need cleaning. Don't forget to release it when the class is destroyed.
Shallow vs Deep Copies
  • Object Copying: An object is automatically copied when passed by value, returned from a function, used as an initialiser or provided to the object's constructor.
  • Copy Constructor: Copies the object using the constructor nomenclature.
  • Assignment Operator: Copies the object when the = (assignment) operator is used.
  • Default: The compiler handily generates these default versions for us and they tend to do a pretty good job of copying objects.
Default Copies
  • Value: The default copy operations simply copies the value of each data member to the new object's data member, known as a 'member-wise copy'.
Heap and Copies
  • Shallow Copy: All the shallow copy does is that it creates another pointer that pointed to the same block of memory on the heap.
  • Deallocation: When one of the objects is destroyed, the block of memory being shared is freed on the heap, leaving the copy with a dangling pointer.
Smart Pointers
  • Smart Pointers: There's a lot of responsibility on the programmer to make sure that memory is released correctly; but to make life easier, smart pointers were invented.
  • C++11: With the recent standard, three new pointer types were added to make working with pointers easier. Auto_ptr is now deprecated as a result.
Unique_Ptr
  • Common Usage: A unique pointer is probably the go-to pointer when using smart pointers.
  • Performance: They are the same size as raw pointers and for most operations they execute the exact same instruction set.
  • Guidance: If a raw pointer is suitable for your program, then it's a reasonable assumption that a unique_ptr also is.
  • Exclusivity: A unique_ptr is exclusive in it's ownership. It always has ownership of the data it points to. Moving from one unique_ptr to another transfers the ownership.
  • Copying: A unique_ptr is exactly that. You don't want two unique_ptr's pointing to the same resource. Hence copying of them is disabled.
  • Why?: When a unique_ptr is destroyed it automatically deletes the memory it points to i.e. dangling pointers.
  • Implicit Conversion: You can't implicitly convert pointers to smart pointers. You need to construct the auto_ptr explicitly.
  • Changing Ownership: We can do this using the reset function on the auto_ptr. Whenever you want to change the smart pointer is managing, use reset.
  • Moving Ownership: We can also change ownership between two unique_ptrs.
Shared_Ptr
  • Dynamic Memory: The lack of garbage collection in C++ is one of the hardest hurdles for new programmers, but shared_ptr allows us the same behaviour.
  • Lifetime: Using shared_ptrs an object's lifetime is managed through shared ownership. No one shared_ptr owns the object.
  • Reference Counted: Instead the shared_ptr tracks all instances that are being managed and only frees the memory when the count is 0.
  • Garbage Collection: Programmers need not worry when the last reference to the memory is destroyed as the object's destruction is now deterministic.
  • Constructors: They simply increase the count and destructors reduce the count.
  • Size: They are twice the size, on pointer for the data and one to keep track of the reference count.
  • Reference Count(1): It's located on the heap, so it comes with all the overheads that allocating on the heap entails.
  • Atomic Reads/Writes: The reference count has to be thread safe. Atomic operations are necessary to keep the threads in sync and are typically slower.
  • Move: When constructing a shared_ptr from another and no longer requiring the original, we should attempt to move rather than copy.
  • Inheritance: Shared pointers also utilise inheritance and have a virtual function (destruction). So there's overhead for memory and cycles here.
  • Reference Count(2): The Reference Count is part of a larger block of memory known as the control block.
  • One Per Shared: For every object that is shared, there is one control block. If an object is shared by five pointers, there's still only one.
  • Contents: 1. The reference count. 2. Custom allocator. 3. Custom deallocator. 4. Other data such as a weak count.
  • Control Blocks: A control block is created when the shared_ptr is created. However, it can't know if one already exists.
  • Make Shared: Std::make_shared will create a new object to point to, so we know it doesn't have a control block.
  • Unique_ptr: When constructing a shared_ptr from a unique one, a control block is always allocated.
  • Raw Pointer: Only use a raw pointer to construct the shared_ptr if you know that it doesn't have a control block i.e. stored as a shared_ptr elsewhere.
Weak_Ptr
  • Weak Pointers: They are pointers that act like shared_ptr's but they do not count towards the ownership of the object.
  • Dereferencing: They can't be dereferenced. Instead you convert them to a shared_ptr before access.
  • Dangling Pointer: It's strength is the ability to check if the object still exists in memory before you can obtain access to it.
  • Atomic Operation: In order for the check to complete and the conversion to a shared_ptr atomic operations are used.
  • Performance: It has the same overheads as the shared_ptr.
  • A Cache: Where we only want read-access but need to guarantee the object still lives.
  • Observer's List: A design pattern that involves other elements (observers) of your software observing the state of specific elements in your game (subjects).
  • Circular Shared_ptrs: When two shared_ptrs point to each other. This forms a deadlock.
After the 'Memory Management' part finished and after the 15 minute break, the next part of the lesson began, which was about Data Structures.

Structs
  • Structure: An array allows you to keep a collection of the same type, where as a struct allows you to combine multiple types in one structure.
  • Grouping: This is useful when we want to group data of different types together, where as an array would not work.
  • Conceptually: The data often stored in a struct is conceptually linked, although not closely enough to be a class.
  • Parameters: Functions with large parameter lists can be altered to use structs which can continue to grow easily.
  • Class-Like: Structs in C++ are actually the equivalent of public classes. Classes are private by default but structs are public.
  • Preference: Prefer classes where it's more than just data that you want to collate i.e. if you want to create member functions etc.
  • Array Support: Because structs have types, they are supported in arrays or container types just like any other.
  • Pointer to Structs: It's legitimate to access the data in a structure using pointers. It follows the same guidance of normal ones.
  • Nested: You can use nest structs within structs if you so choose to do so.
Containers
  • Types: Containers allow us to store objects collectively.
  • Examples: Arrays, Linked Lists, Associative i.e. maps, Unordered, Stacks.
  • Stack: We already know how a stack works, we discussed it when we spoke about memory allocation and the call stack frames.
  • Container Library: C++ provides a container library for these type of implementation, saving you the time and effort.
Vector
  • Arrays(1): Up until now, we've been focusing on C style arrays. Let's look at the container version most used instead.
  • Vectors(1): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Internally: They are dynamically allocated arrays under the hood. Their power comes from runtime ability to change size.
  • Reallocation: Once the capacity of the vector is reached, the array will be resized.
  • Why?: Containers offer us more flexibility including iteration.
  • Capacity: The array stored in the vector has a limited capacity. When reached, it's extended.
  • Vectors(2): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Allocated Memory: To prevent excessive memory allocations and the cost of moving objects on the heap, the array normally has a reserve capacity.
  • Memory Usage: Memory Usage is higher than necessary because of this. Often the programmer sets a reasonable capacity to begin with.
  • Efficiency: Vectors are fantastic at iterating through objects and at adding new objects to the beginning and the end of the container.
  • Arrays(2): When you need an array, especially one on the heap, then the vector should be your choice.
  • Iterators: Containers use iterators for deciding on how to navigate the array. You can use iterators instead of range based loops; if you want.
With the lectural side of the lesson over, we moved onto the practical side of the lesson. In this practical session, we were given a new project to work on. I didn't managed to get a lot done, ending with copying/moving the lib file from one project's file to another, due to the confusion of where the project needed to be extracted.

No comments:

Post a Comment