Nick Allen
Nick Allen

Reputation: 1873

What is the elegant way to delete tmpfile created by boost::filesystem?

I had a code snippet

        if (!boost::filesystem::exists(tempDir)) {
            boost::filesystem::create_directories(tempDir);
        }
        auto path = tempDir / boost::filesystem::unique_path("gfbfv1-%%%%-old");
        do_something_maythrow(path);
        remove(path);

How can I ensure that path is always deleted even in case of do_something_maythrow throwing?

Should I write a FileDeleter which takes a path and remove that path on destructor which utilize the so-called RAII concept or is there an existing solution?

Upvotes: 0

Views: 392

Answers (1)

eerorika
eerorika

Reputation: 238361

Should I write a FileDeleter which takes a path and remove that path on destructor which utilize the so-called RAII concept

This is a fairly reasonable solution. Be careful to take care of any exceptions that the deletion may raise because you wouldn't want to throw from a destructor, especially from one that is being executed because of a thrown exception.

However, if this is not a commonly needed structure, and therefore there isn't a need for a reusable solution, then a simple ad-hoc alternative is to use ScopeExit also known as Scope Guard.

Upvotes: 1

Related Questions