在c++中可以藉助RAII來完成對對象地處理,避免到處異常釋放對應地資源。
#ifndef __ONCE_RAII_H__
#define __ONCE_RAII_H__
#include <functional>
using namespace std;
namespace toolkit {
class onceRAII {
public:
typedef function<void(void)> task;
onceRAII(const task &onConstructed, const task &onDestructed = nullptr) {
if (onConstructed) {
onConstructed();
}
_onDestructed = onDestructed;
}
onceRAII(const task &onConstructed, task &&onDestructed) {
if (onConstructed) {
onConstructed();
}
_onDestructed = std::move(onDestructed);
}
~onceRAII() {
if (_onDestructed) {
_onDestructed();
}
}
private:
onceRAII();
onceRAII(const onceRAII &);
onceRAII(onceRAII &&);
onceRAII &operator =(const onceRAII &) = delete;
onceRAII &operator =(onceRAII &&) = delete;
task _onDestructed;
};
}//namespace toolkit
#endif //__ONCE_RAII_H__
#include <iostream>
#include <thread>
#include "onceRAII.h"
using namespace std;
using namespace toolkit;
int main()
{
bool flag = false; //測試標識
{
onceRAII oncetest([&]() {
flag = true;
cout << "測試開始" << endl;
}, [&]() {
flag = false;
cout << "測試終止" << endl;
});
std::this_thread::sleep_for(std::chrono::seconds(2));
}
system("pause");
return 0;
}