利用局部对象离开作用域,自动调用析构函数。
类似应用:lock_guard<> ,及时加解锁,防止死锁。
学习例子:
#include <bits/stdc++.h>
#define rep( i , j , n ) for ( int i = int(j) ; i < int(n) ; ++i )
#define dew( i , j , n ) for ( int i = int(n-1) ; i > int(j) ; --i )
#define _PATH __FILE__ , __LINE__
typedef std::pair < int , int > P ;
using std::cin ;
using std::cout ;
using std::endl ;
using std::string ;
namespace YHL {
// 模板类实现简易 RAII, 类似于智能指针
template< typename T >
class myRAII {
private:
T *ptr ;
myRAII(const myRAII&) = delete ;
myRAII& operator=(const myRAII&) = delete ;
public:
explicit myRAII(T *_ptr) : ptr(_ptr) {}
~myRAII() {
if ( ptr not_eq nullptr )
delete ptr ;
ptr = nullptr ;
}
T& operator*() const { return *ptr ; }
T* get() { return ptr ; }
} ;
}
class Task {
private:
class threads {
public:
threads() { cout << "构造 threads" << endl ; }
~threads() { cout << "访问 threads 析构器" << endl ; }
} ;
YHL::myRAII<threads> childTask1 ;
YHL::myRAII<threads> childTask2 ;
public:
// 两个 childTask 无论如何都会访问析构器, 任何一个构造失败都不会妨碍另一个资源泄露
Task() : childTask1( new threads() ) ,
childTask2( new threads() ) {
cout << "两个子任务获取资源成功!" << endl ;
}
~Task() {
cout << "两个子任务析构就绪" << endl ;
}
} ;
int main () {
Task task1 ;
return 0 ;
}