Tags: lec11

Q: Why might you need to do reference counting in a language like Python or Java?
A: Because heap memory is the only resource that the garbage collector helps you clean up.
For other resources (e.g., file handles, sockets, locks, etc.), it's your job to cleanup when you're done!
In some cases, a resource is only used for a short block of code, and you can use a "with" or "try/finally" to manage resources, but for more complicated cases you'll need to do some bookkeeping work to know when your program is completely done with the resource.

Q: What does RAII stand for?
A: Resource Acquisition Is Initialization

Q: How does RAII make use of constructors/destructrors?
A: constructor allocates a resource, destructor releases a resource

Q: In RAII, what is an "owner"?
A: An owner is a regular object (e.g., created from a class) that refers to one or more resources (e.g., it could be a pointer to heap memory, a file handle, etc) and is responsible for cleanup.

Q: What is a popular way of managing heap memory in C++ that follows the RAII pattern?
A: Smart pointers!  For example, a unique_ptr "owns" some memory on the heap, and is responsible for releasing that memory at the end of the unique_ptr's lifetime (e.g., when it is popped off the stack).

Q: What does "exception safety" mean in the context of resource management?
A: It means we won't leak resources just because there is an exception at an inconvenient point in time.

Q: What are some advantages of using make_unique and make_shared instead of directly creating a unique_ptr or shared_ptr?
A: 1. more concise code (avoid repeating type name)
2. don't have "new" in the code (in modern C++, there are usually better ways to do things that don't involve "new", so this is something you might search for in the code
3. exception safety (if there's an exception during a constructor call for an object on the heap)
4. in the case of shared_ptr, we'll get a more compact memory layout where the control block is immediately before the corresponding object on the heap

Q: What's a common scenario where shared_ptr's might leak?
A: Cyclic references.  For example, if A references B and B references A, then neither object will ever be freed, even if there is no way to reach either of these objects from the variables that are still in scope.