I happened to stumble upon this post on Stack Overflow: make shared_ptr not use delete
and I have a related question from the C++ standard library book by Nicolai M. Josuttis. Below is the following piece of code from the book:
#include <string>
#include <fstream> // for ofstream
#include <memory> // for shared_ptr
#include <cstdio> // for remove()
class FileDeleter
{
private:
std::string filename;
public:
FileDeleter (const std::string& fn)
: filename(fn) {
}
void operator () (std::ofstream* fp) {
delete fp; // close file
std::remove(filename.c_str()); // delete file
}
};
int main()
{
// create and open temporary file:
std::shared_ptr<std::ofstream> fp(new std::ofstream("tmpfile.txt"),
FileDeleter("tmpfile.txt"));
//...
}
I understand that the signature of the deleter function should be of the following :
void Deleter(T* p)
So in the above example, how is it that the deleter function (specified as FileDeleter("tmpfile.txt")) looks to be a constructor call for the class rather than a function with the above format? How does the deleter function actually get invoked on destruction of the shared pointer here?