我想在需要时推送一系列清理功能。我使用 atexit 为一个没有任何参数的清理函数执行此操作,但我不确定如何将这种方法扩展到多个清理函数。我对 boost::bind 不是很熟悉,但我认为这是个好主意,因为这就是我将函数绑定(bind)到线程的方式...
在 C++ 中,我试图让以下内容工作:
函数定义
static void closeAnimation(string prefix="");// static member of fileWriter
代码:
atexit(boost::bind(fileWriter::closeAnimation, "0")); // I want to first prefix to be "0"
错误:
cannot convert ‘boost::_bi::bind_t<void, void (*)(std::basic_string<char>), boost::_bi::list1<boost::_bi::value<const char*> > >’ to ‘void (*)()’ for argument
提前致谢!
最佳答案
没有“不使代码复杂化的单行解决方案”。
最糟糕的解决方案是将该参数存储在全局变量中,并在 atexit
处理程序中检索它
由于您使用的是 C++,因此静态变量的析构函数也可以用作 atexit
处理程序。然后您可以在该静态变量的构造函数中传递参数以进行参数化,例如
struct AtExitAnimationCloser
{
const char* _which_param;
AtExitAnimationCloser(const char* which_param) : _which_param(which_param) {}
~AtExitAnimationCloser() { FileWriter::closeAnimation(_which_param); }
};
void f()
{
printf("entering f\n");
static AtExitAnimationCloser s0 ("0"); // registers closeAnimation("0") at exit
static AtExitAnimationCloser s1 ("1"); // registers closeAnimation("1") at exit
printf("leaving f\n");
}
演示:http://www.ideone.com/bfYnY
注意静态变量绑定(bind)到它们的名字,所以你不能说
for (it = vecs.begin(); it != vecs.end(); ++ it)
{
static AtExitAnimationCloser s (*it);
}
为所有内容调用atexit
。但是你可以让静态变量本身占据整个范围
static AnotherAtExitAnimationCloser s (vecs.begin(), vecs.end())
最后,使用惯用的 C++,我认为您不需要使用这些技巧...您可以存储 T
类型的 vector ,它在销毁时 ~T
调用 fileWriter::closeAnimation
。
关于c++ - 将值传递给 atexit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8053000/