#include <iostream>
#include <string>
#include <memory>
#define defer(fun,p) std::shared_ptr<void> defer_##p(p,std::bind(fun,std::placeholders::_1))
void fun(int *p) {
std::cout << "p = " << *p << std::endl;
}
int main() {
int a = 10;
int *p = &a;
defer(fun, p);
std::cout << "hello world." << std::endl;
return 0;
}
本文介绍了一种在C++中实现延迟执行的技巧,通过使用std::shared_ptr和std::bind,可以在特定条件下调用函数,例如在资源释放前执行某些操作。这种技巧对于需要在对象销毁时执行清理工作的场景特别有用。
175

被折叠的 条评论
为什么被折叠?



