C++编程(C)

Educn 1461 int f throwstdbadalloc int f void

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: t char* n, const char* a){p=fopen(n,a);} File_ptr(FILE* pp) { p=pp; } // 适当的复制机制 ~File_ptr() { if(p) fclose(p); } operator FILE*() { return p; } }; 这样处理,主程序只需要一句话 File_ptr f(fn,”r”); 析构函数总会被调用,资源总会被释放 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 14.4.1 构造函数和析构函数的使用 利用局部对象管理资源的技术通常被称为 “资源申请即初始化(resource acquisition is initialization)” 只有在一个对象的构造函数执行完毕时,这 个对象才被看作已经建立起来了,只有在此 之后,异常产生时的堆栈回退才为该对象调 用析构函数 一个由子对象组成的对象的构造将一直持续 到它所有的子对象都完成了构造 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 示例 class X{ File_ptr aa; Lock_ptr bb; public: X(const char* x, const char* y) :aa(x,"rw"), // 申请'x' bb(y)// 申请y {} }; 考虑X,构造函数需要两种资 源,...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online