Reputation: 45091
Context:
Suppose an external library requires that its globalCleanup()
function gets called in order to assure all its resources are cleaned up (it might allocate some global resources during any of its calls.) A client function client()
does this before each of its many return
s but of course this is not exception-safe and the code is repetitive.
Problem:
Is there an elegant way to assure this global function gets called on the client()
exit? Defining a dummy class whose only purpose is to call a global function in the destructor (RAII style) is an option, but maybe there's something simpler?
TLDR: How to call a global cleanup function RAII-style?
Upvotes: 1
Views: 562
Reputation: 1993
#include "loki/ScopeGuard.h"
client()
{
LOKI_ON_BLOCK_EXIT(globalCleanup);
// some codes here
} // globalCleanup will be called when exit this block
Upvotes: 2
Reputation: 67213
Wrapping it a class that cleans up in the destructor seems like the best choice to me. (Assuming the library isn't implemented as classes already.)
Upvotes: 0
Reputation: 15513
class Cleaner {
public:
Cleaner() {}
~Cleaner() { ExtLib::CleanGlobal(); }
};
void client() {
Cleaner cleaner;
// Code that works with ExtLib
}
Upvotes: 5