用auto_ptr类模板帮助动态内存管理
赵湘宁
void g() //可能掷出 { if (some_condition == false) throw X(); } void func() { string * pstr = new string; g(); //如果 g 掷出一个异常,内存溢出 delete pstr; //如果 g 掷出一个异常,则此行为不能达到的代码行。 } int main() { try { func(); } catch(...) {} }
许多数据重要的结构以及应用,象链表,STL容器,串,数据库系统以及交互式应用必须使用动态内存分配,因此仍然冒着万一发生异常导致内存溢出的风险。C++标准化委员会意识到了这个漏洞并在标准库中添加了一个特殊的类模板,它就是std::auto_ptr,其目的是促使动态内存和异常之前进行平滑的交互。Auto_ptr保证当异常掷出时分配的对象(即:new操作符分配的对象)能被自动销毁,内存能被自动释放。下面我们就来讨论使用动态内存时,如何正确和有效地使用auto_ptr来避免资源溢出。这个技术适用于文件,线程,锁定以及与此类似的资源。 Auto_ptr的定义可以在<memory.h>中找到。与标准库中其它的成员一样,它被声明在命名空间std::中。当你实例化auto_ptr对象时,对它进行初始化的方法是用一个指针指向动态分配的对象,下面是实例化和初始化auto_ptr对象的例子:
include <memory> #include <string> using namespace std; void func() { auto_ptr<string> pstr (new string); /* 创建并初始化auto_ptr */ }
auto_ptr<string> pstr = new string; //编译出错
auto_ptr<int> pi (new int);
*pstr = "hello world"; //赋值 pstr->size(); //调用成员函数
void func() { auto_ptr<string> pstr (new string); g(); //如果g()掷出异常,pstr 被自动摧毁 }
auto_ptr<char> pstr (new char[12] ); //数组;为定义