Help dynamic memory management with the Auto_ptr class template

Source: Internet
Author: User
Tags exception handling memory usage

The most dynamic memory usage is in the code of the C + + application. Programmers with experience in programming know that the use of the new operator must match the delete, and in some cases there may still be a memory overflow. When an exception is thrown, the normal control flow of the program is changed, causing a potential memory overflow. For example

void g() //可能掷出
{
  if (some_condition == false)
   throw X();
}
void func()
{
  string * pstr = new string;
  g(); //如果 g 掷出一个异常,内存溢出
  delete pstr; //如果 g 掷出一个异常,则此行为不能达到的代码行。
}
int main()
{
  try
  {
   func();
  }
  catch(...)
  {}
}

When G throws an exception, the exception handling mechanism expands the stack: g () exits, while controlling the catch (...) being moved to main (). code block. At this point, no matter what, the DELETE statement in Func () is not executed, resulting in a pstr memory overflow. If you use local automatic string variables instead of using dynamic allocations-the memory overflow does not occur:string str; //局部自动对象
g(); //没有内存溢出

Many data-critical structures as well as applications such as linked lists, STL containers, strings, database systems, and interactive applications must use dynamic memory allocations, and therefore still risk a memory overflow in the event of an exception. The C + + Standardization Committee was aware of this vulnerability and added a special class template to the standard library, which is std::auto_ptr, to facilitate smooth interaction between dynamic memory and the exception. Auto_ptr guarantees that the objects allocated when an exception is thrown (i.e., objects assigned by the new operator) can be automatically destroyed and memory can be automatically released. Let's discuss how to use auto_ptr correctly and effectively to avoid resource overruns when using dynamic memory. This technique applies to files, threads, locks, and similar resources.

The definition of auto_ptr can be found in <memory.h>. As with other members of the standard library, it is declared in the namespace std::. When you instantiate a Auto_ptr object, the way to initialize it is to use a pointer to the dynamically allocated object, and here is an example of instantiating and initializing the Auto_ptr object:

#include <memory>
#include <string>
using namespace std;
void func()
{
  auto_ptr<string> pstr (new string); /* 创建并初始化auto_ptr */
}

The type of the auto_ptr pointer is specified in the Auto_ptr bracket followed by a string in this example. Then auto_ptr the name of the handle, in this case is pstr. Finally, the instance is initialized with the dynamically allocated object pointer. Note that you can only use a copy of the Auto_ptr constructor, which means the following code is illegal:

auto_ptr<string> pstr = new string; //编译出错

Auto_ptr is a template, so it is completely generic. It can point to any type of object, including the basic data type:

auto_ptr<int> pi (new int);

Once you instantiate a auto_ptr and initialize it with the dynamically assigned object address, you can use it as a normal object pointer, for example:

*pstr = "hello world"; //赋值
 pstr->size(); //调用成员函数

This is done because the auto_ptr overloads the operator &,* and->. Don't be misled by grammar, remember that PSTR is an object, not a pointer.

How does auto_ptr solve the memory overflow problem mentioned earlier? The Auto_ptr destructor automatically destroys the dynamically allocated object it binds to. In other words, when a pstr destructor executes, it deletes the string pointers created during construction pstr. You must not delete auto_ptr because it is a local object and its destructor is invoked automatically. Let's take a look at the revised version of function Func (), which uses auto_ptr:

void func()
 {
  auto_ptr<string> pstr (new string);
  g(); //如果g()掷出异常,pstr 被自动摧毁
 }

C + + guarantees that objects of the automatic storage type are automatically destroyed during the stack expansion process. Therefore, if G () throws an exception, the destructor of the PSTR will be transferred to the catch (...) in the control. Block before executing. Because the Pstr destructor deletes its bound string pointer, there is no memory overflow to occur. In this way, we use auto_ptr to implement automatic and secure local objects when using dynamically allocated objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.