5. (Custom Deleter) Shared and unique pointers support deleters. A deleter is a callable object that executes
Question:
5. (Custom Deleter)
Shared and unique pointers support deleters. A deleter is a callable object that executes some code before an object goes out of scope. A deleter can be seen as a kind of callback function. We first give a simple example to show what we mean: we create twodimensional points as smart pointers. Just before a point goes out of scope a callback function will be called:
auto deleter = [](Point* pt)-> void { std::cout << "Bye:" << *pt; };
The corresponding code is:
using SmartPoint = std::shared_ptr
SmartPoint p1(new Point(), deleter);
We now discuss the exercise. To this end, answer the following questions:
a) The goal of this exercise is to open a file, write some records to the file and then close it when we are finished. Under normal circumstances we are able to close the file. However, if an exception occurs before the file has been closed the file pointer will remain open and hence it cannot be accessed. In order to ensure exception safety we employ a shared pointer with a deleter in the constructor, for example by using a function object:
std::shared_ptr
where FileFinalizer is a function object. Similar to the deleter that we gave at the beginning of the exercise.
b) Create a free function and a stored lambda function that also play the role of custom deleters for this problem.
c) Test the code for the three kinds of deleter function (function object, free function, lambda function).
d) Create a small loop in which records are added to the file; throw an exception at some stage in the loop, catch the exception and then open the file again. Does it work?
Step by Step Answer: