menu

hjk41的日志

Avatar

More Effective C++ 9: Use destructors to prevent resource leaks

Exception handling makes us as much trouble as they solve.


string * a=new string;
try{
    ifstream file("kk.txt");
    file>>*a;
    ...
}catch (exception & e){
    ...
    delete a;
    throw;
}
delete a;


In order to prevent the possible memory leak caused by exception, we have to write delete a twice. And if there is more pointers, we will have to duplicate more code.
However, if we can encapsulate the pointer into an object, things will be easier. Destructors of objects will be called when the objects get out of scope, no matter how. However, we don't have to implement the encapsulator ourselves, because C++ already have it. It is called auto_ptr
For the preceding example, we can write it like this:


auto_ptr<string>a=new string;
try{
    ifstream file("kk.txt");
    file>>*a;
    ...
}catch (exception & e){
    ...
    throw;
}


We don't need to delete the pointer, the destructor of auto_ptr will do it for us. The declaration of auto_ptr may look like this:

template<class T>
class auto_ptr {
public:
  auto_ptr(T *p = 0): ptr(p) {}        // save ptr to object
  ~auto_ptr() { delete ptr; }          // delete ptr to object
private:
  T *ptr;                              // raw ptr to object
};

评论已关闭