Smart pointer (smart pointer) (1): auto_ptr

Source: Internet
Author: User

Smart pointers address the issue of resource lifetime management (especially dynamically allocated objects). Smart pointers are available in a variety of different styles. Most have a common key feature: automatic resource management. This feature may appear in different ways: such as the lifetime control of dynamically allocated objects, and the acquisition and release of resources (files, network Connections). Here we discuss the first case, which holds pointers to dynamically allocated objects and deletes them at the correct time.

When do we need smart pointers?
There are three typical scenarios for using smart pointers:
? Sharing of ownership of resources
? To write code that is unusually secure
? Avoid common errors, such as resource leaks
Share ownership when multiple objects need to use a third object at the same time. How (or when) should this third object be released? In order to ensure that the time to release is correct, each object that uses this shared resource must know each other to be able to accurately grasp the release time of the resource. From a design or maintenance standpoint, this coupling is not feasible. A better approach is to have these resource owners delegate the lifetime management responsibility of resources to a smart pointer. When no sharer exists, the smart pointer can safely release the resource.
Exceptionally safe, simply to say that there is no resource leak when the exception is thrown and that the state of the program is consistent. If an object is dynamically allocated, it will not be deleted when the exception is thrown. Because the stack expands and the pointer leaves the scope, the resource can leak until the program ends (even if the resource collection at the end of the program is not guaranteed by the language). Not only can programs run out of resources due to memory leaks, but the state of the program can also become confusing. Smart pointers can automatically release these resources for you, even in the event of an exception.
Avoid common mistakes. For example, forget to call Delete, OK, this will not have to say more.

Let's see Std::auto_ptr first.
Template class Auto_ptr;
Automatic Pointer [deprecated]
Note:this class template is deprecated as of c++11. Unique_ptr is a new facility with a similar functionality, but with improved security (no fake copy assignments), added FE Atures (deleters) and support for arrays. See Unique_ptr for additional information.
This class template provides a limited garbage collection facility for pointers, by allowing pointers to the elements They point to automatically destroyed when the Auto_ptr object is itself destroyed.
Auto_ptr objects had the peculiarity of taking ownership of the pointers assigned to Them:an Auto_ptr object which has OW Nership over one element are in charge of destroying the element it points to and deallocate the memory allocated to it When itself is destroyed. The destructor does this by calling operator delete automatically.
Therefore, no, auto_ptr objects should own the same element, since both would try to destruct them at some point. When a assignment operation takes place between the Auto_ptr objects, ownership was transferred, which means that the Obje CT losing ownership is set to no longer point to the element (it was set to the null pointer).

A simple implementation of a auto_ptr:

Template<classX>class auto_ptr{Private: x* ptr;mutable BOOLowns; Public:typedefX Element_type;Explicit auto_ptr(x* p =0) __stl_nothrow:ptr (P), owns (p) {}auto_ptr(Const auto_ptr& A) __stl_nothrow:ptr (A.ptr), owns (a.owns) {a.owns =0; }Template<classT>auto_ptr(Const auto_ptr<T>& a) __stl_nothrow:ptr (A.ptr), owns (a.owns) {a.owns =0; }auto_ptr&operator=(Const auto_ptr& A) __stl_nothrow {if(&a! = This) {if(owns)Deleteptr      owns = a.owns;      ptr = a.ptr; A.owns =0; }  }Template<classT>auto_ptr&operator=(Const auto_ptr<T>& a) __stl_nothrow {if(&a! = This) {if(owns)Deleteptr      owns = a.owns;      ptr = a.ptr; A.owns =0; }  }  ~auto_ptr() {if(owns)Deleteptr }};

When it is destructor, it is automatically called Delete, that's it.
  
Let's look at an example:

//auto_ptr::operator= ExampleInclude <iostream>include <memory>intMain () {STD::auto_ptr<int> P;STD::auto_ptr<int> p2; p =STD::auto_ptr<int> (New int); *p = One; P2 = p;STD::cout<<"P2 points to"<< *P2 <<' \ n ';//(P is now null-pointer auto_ptr)  return 0;}//output:p2 points to one

AUTO_PTR implementation key points:
1. Use the feature "the object on the stack is automatically refactored when it leaves the scope."
2. For dynamically allocated memory, its scope is manual control by the programmer, which gives the programmer a convenient but inevitably inadvertently caused by the memory leak, after all, only the compiler is the most reliable.
3. Auto_ptr by constructing an object A on the stack, wrap the pointer p for dynamically allocating memory in object A, all operations on pointer p are converted to object A. In A's destructor, the space of P is automatically freed, and the destructor is automatically called by the compiler without the programmer worrying

Smart pointer (smart pointer) (1): auto_ptr

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.