CPSC 427: Object-Oriented Programming

Michael J. Fischer

Lecture 13
March 3, 2016

Smart Pointer Demo

Dangling pointers Pointers can be used to permit object sharing from different contexts.

One can have a single object of some type T with many pointers in different contexts that all point to that object.

Problems with shared objects

If the different contexts have different lifetimes, the problem is to know when it is safe to delete the object.

It can be difficult to know when an object should be deleted. Failure to delete an object will cause memory leaks.

If the object is deleted while there are still points pointing to it, then those pointers become invalid. We call these dangling pointers.

Failure to delete or premature deletion of objects are common sources of errors in C++.

Avoiding dangling pointers

There are several ways to avoid dangling pointers.

1.
Have a top-level manager whose lifetime exceeds that of all of the pointers take responsibility for deleting the objects.
2.
Use a garbage collection. (This is java’s approach.)
3.
Use reference counts. That is, keep track somehow of the number of outstanding pointers to an object. When the last pointer is deleted, then the object is deleted at that time.

Modern C++ Smart Pointers

Modern C++ has three kinds of smart pointers. These are objects that act very much like raw pointers, but they take responsibility for managing the objects they point at and deleting them when appropriate.

We will discuss them later in the course. For now, we present a much-simplified version of shared pointer so that you can see the basic mechanism that underlies all of the various kinds of shared pointers.

Smart pointers

We define a class SPtr of reference-counted pointer-like objects.

An SPtr should act like a pointer to a T.

This means if sp is an SPtr, then *sp is a T&.

We need a way to create a smart pointer and to create copies of them.

Demo 13-SmartPointer illustrates how this can be done.

More on Course Goals

Low-level details

Example picky detail

Efficient use of resources

Efficiency is concerned with making good use of available resources:

Strategy for improving efficiency: Reuse and recycle. Maintain a pool of currently unused objects and reuse rather than recreate when possible.

In the case of memory blocks, this pool is often called a free list.

Efficiency measurement

A first step to improving efficiency is to know how the resources are being used.

Measuring resource usage is not always easy.

The next demo is concerned with measuring execution time.

Clocks and Time Measurement

How to measure run time of a program

High resolution clocks

Measuring time in real systems