Skip to content

Instantly share code, notes, and snippets.

@cjhanks
Created December 10, 2015 12:04
Show Gist options
  • Save cjhanks/83875fdd2c81a3912ff2 to your computer and use it in GitHub Desktop.
Save cjhanks/83875fdd2c81a3912ff2 to your computer and use it in GitHub Desktop.
on_exit Handler
#include "ExitHandler.hpp"
#include <cstdlib>
#include <vector>
namespace ExitHandler {
namespace {
std::vector<AtExitFunctor> Functors;
void
AtExitHandler()
{
for (const auto& functor: Functors) {
functor();
}
}
} // ns
bool
RegisterAtExit(AtExitFunctor functor)
{
Functors.emplace_back(functor);
// upon registering the first functor, register the atexit handler
if (1 == Functors.size()) {
return std::atexit(AtExitHandler) == 0;
} else {
return true;
}
}
} // ns ExitHandler
#if EXAMPLE_USAGE
#include <iostream>
void
testFunction(int k) {
std::cerr << "k = " << k << std::endl;
}
int
main(void)
{
ExitHandler::RegisterAtExit(testFunction, 3);
ExitHandler::RegisterAtExit(testFunction, 4);
}
#endif // EXAMPLE_USAGE
////////////////////////////////////////////////////////////////////////////////
// License: Free as in 'bird'.
// A set of functions for C++ which mimic the non-portable `on_exit` function
// with a C++11 twist.
//
// This is especially necessary when signal handlers are out of your control and
// you need to clean up some resources.
//
// Usage:
// void
// someArbitraryFunction(std::string* pointerToDelete)
// {
// delete pointerToDelete;
// }
//
// int
// main(void)
// {
// auto s = new std::string("Words!");
// ExitHandler::RegisterAtExit(someArbitraryFunction, s);
// }
////////////////////////////////////////////////////////////////////////////////
#ifndef EXIT_HANDLER_HPP_
#define EXIT_HANDLER_HPP_
#include <functional>
namespace ExitHandler {
using AtExitFunctor = std::function<void(void)>;
bool
RegisterAtExit(AtExitFunctor functor);
template <typename... _Args>
bool
RegisterAtExit(void(*functor)(_Args...),
_Args&&... args)
{
return RegisterAtExit(std::bind(functor, std::forward<_Args...>(args...)));
}
template <typename... _Args>
bool
RegisterAtExit(std::function<void(_Args...)> functor,
_Args&&... args)
{
return RegisterAtExit(std::bind(functor, std::forward<_Args...>(args...)));
}
} // ns ExitHandler
#endif // EXIT_HANDLER_HPP_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment