Answer the following questions about smart pointers:

a) Briefly describe the advantages of shared_ptr over auto_ptr.
b) Describe a situation in which a custom deleter function would be used.
c) Describe a situation in which you’d use a weak_ptr that is not responsible for lifetime management of its resource.

a) Multiple shared_ptrs can point to a resource, but only one auto_ptr can point to a given resource. When you copy an auto_ptr you can only access the resource through the new auto_ptr. Because of the ability to be copied, shared_ptrs can be used in STL containers and algorithms; auto-ptrs cannot. shared_ptrs can also be used to point to an array by providing a custom deleter function object that calls delete[] instead of delete.
b) A custom deleter function would be used when a shared_ptr points to a dynamically allocated array of objects. Another use would be when a shared_ptr points to an object that manages a file, database or network connection.
c) A common use of weak_ptrs is when two objects each store pointers to one another. This prevents a possible memory leak when the objects go out of scope.

Computer Science & Information Technology

You might also like to view...

Too much text on a slide usually requires a smaller ________ size that can be difficult to read by the audience

Fill in the blank(s) with correct word

Computer Science & Information Technology

The Cut command duplicates a selection and places it in the Clipboard

Indicate whether the statement is true or false

Computer Science & Information Technology