avish
avish

Reputation: 61

Calling custom deleter class member function for shared pointer

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?

Upvotes: 0

Views: 1055

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

FileDeleter("tmpfile.txt") creates a deleter object to pass to the shared pointer.

The shared pointer's implementation stores a copy this somewhere as a variable, as well as the managed object, along the lines of

std::ofstream * object;
FileDeleter deleter;

The shared pointer's destructor will invoke this as

deleter(object);

which will call the deleter's overloaded operator(), deleting the object and removing the file.

Upvotes: 1

Related Questions