CS 70

Key Points

  • Sometimes a class needs to manage memory on the heap.
    • We allocate that memory using new, either in its constructor(s) or in other member functions. The new operation
      • Allocates memory on the heap (requesting it from the system's heap manager).
      • Constructs the object (or objects) in that space.
      • Returns a pointer to the memory. We'll need to eventually give this pointer to the appropriate delete.
    • Our classes own their resources, therefore the class also owns the memory it allocates on the heap—in other words, it's responsible for that memory.
      • In our classes, ownership is exclusive. If two objects both think they own the same data, it's a bug.
  • A class's destructor must release all memory in the heap that the object is responsible for.
    • The synthesized destructor will simply destroy each data member of an instance of a class.
    • If a data member is a pointer that is storing the location of memory on the heap, that memory will not be destroyed and deallocated when the pointer is destroyed.
    • Failing to deallocate heap memory that our object is responsible for can cause memory leaks, where an object is gone, but the dynamically allocated data that it owned is still occupying memory but is inaccessible.
    • We release heap memory via a delete statement, which
      • Takes a pointer (that came from new).
      • Destroys the object at that memory address.
      • Deallocates the memory (giving it back to the system's heap manager).
  • A class's copy constructor should be sure to create a deep copy by allocating new heap memory for a new instance of a class.
    • The synthesized copy constructor will simply copy initialize or construct each data member (shallow copy).
    • If one of the data members is a pointer to heap memory, then two objects will both point to the same heap memory!
    • This situation can cause all kinds of trouble, including double-delete errors, if they both objects try to delete that memory.
  • A class's assignment operator should be sure to clean up "old" memory in an instance of a class, then allocate new heap memory for the new configuration of the class instance.
    • The copy-and-swap idiom is a clever/elegant way to do this.
    • A less elegant but more direct way is to first use code from the destructor, then use code from the copy constructor.
  • Alternatively, if we don't think a copy constructor or assignment operator is needed, we can instead choose not to provide them. (Or, during development we can disable them, and then write them last once everything else is done.)

(When logged in, completion status appears here.)