资源获取即初始化RAII
2015-02-28 18:33
337 查看
//class Resource { //public: // Resource(parms p): r(allocate(p)) { } // ~Resource() { release(r); } // // also need to define copy and assignment //private: // resource_type *r; // resource managed by this type // resource_type *allocate(parms p); // allocate this resource // void release(resource_type*); // free this resource //}; //void fcn() //{ // Resource res(args); // allocates resource_type // // code that might throw an exception // // if exception occurs, destructor for res is run automatically // // ... //} // res goes out of scope and is destroyed automatically #include <exception> #include <iostream> #include <unistd.h> #include <stdexcept> class Resource { public: // 不用allocate这个函数时,可以使用这个构造函数也是一样的 //Resource(int const & number) : r(new int [number]()) //{ // std::cout << "allocate 4k bytes" << std::endl; //} Resource(int const & number) : r(allocate(number)) { } ~Resource() { release(r); } private: // I as a programmer, believe this function may throw exception int* allocate(const int & number) const { std::cout << "allocate 4k bytes " << std::endl; return new int[number](); // 小括号表示初始化为0,在linux下这句话也是编不过的,必须把小括号拿掉 } // I as a programmer, believe that this function will not throw exception void release(int* pRes) const throw() { std::cout << "free 4k bytes " << std::endl; delete [] pRes; // delete pRes; } int* r; }; void fcn() throw() { usleep(1000); Resource const res(1024); } void fcn2() throw(std::logic_error) // 程序员认为这个函数可能抛出std::exception类型或者其派生类类型的异常 { usleep(1000); Resource const res(1000); // throw std::exception("a! yi chang le!!!"); throw std::logic_error("a! yi chang le!!!"); } int main() { //while(true) // 用来验证我的RAII是不是好用,一是注释析构中的release,然后取消注释,通过任务管理器能看的很清楚 //{ // fcn(); //} // 把上面注释起来,下面用来看出异常时,能否有效 while(true) { try { fcn2(); } catch(std::exception const & e) { std::cout << e.what() << std::endl; } } return 0; }
相关文章推荐
- RAII技术--获取资源即初始化
- RAII-获取资源即初始化
- RAII:资源获取即初始化
- RAII 资源获取就是初始化
- C++必知必会 - RAII(资源获取及初始化)
- RAII,也称为“资源获取就是初始化”
- RAII:资源获取即初始化(resourse acquisition is initialization)
- RAII(Resource Acquisition Is Initialization:资源获取即初始化)
- RAII:资源获取即初始化
- 资源获取即初始化【RAII】
- RAII(Resource Acquisition Is Initialization资源获取即初始化 )思想
- 类初始化顺序,及获取资源
- boost学习之RAII机制(资源申请即初始化)
- RAII资源请求即初始化
- RAII(Resource Acquisition Is Initialization)资源获得式初始化
- 浅谈----RAII资源获得即初始化(Resource Acquisition Is Initialization)
- 小圆点初始化及资源的获取
- c++ RAII 资源管理就是初始化
- (18)servletContext应用:获取web应用的初始化参数、实现servlet转发、利用servletContext对象读取资源文件
- 5.Boost之“资源申请即初始化” RAII