C ++ smart pointer auto_ptr class

Source: Internet
Author: User

 

Reprinted from: http://www.cnblogs.com/mydomain/archive/2011/04/15/2017424.html

 

1. auto_ptr is the "resource allocation is initialization" class provided by the standard library. It is a template that accepts a type parameter and provides exception security features for dynamically assigned objects. It is defined in the memory header file.

2. auto_ptr operation

Auto_ptr <t> aP;

Create an unbound auto_ptr object named AP

Auto_ptr <t> aP (P );

Create an auto_ptr object named AP. The AP has the object pointed to by the pointer p. The constructor is explicit.

Auto_ptr <t> AP1 (AP2 );

Create an auto_ptr object named AP1, and AP1 saves the pointer originally stored in ap2. Transfers ownership to AP1, and AP2 becomes unbound auto_ptr object

AP1 = AP2

Transfer ownership AP2 to ap1. Delete the object to which AP1 points and make AP1 point to the object to which AP2 points, so that AP2 becomes unbound

~ AP

Destructor. Delete the object to which the AP points

* AP

Returns the reference to the object bound to the AP.

AP->

Returns the pointer saved by the AP.

AP. Reset (P)

If the P value is different from the AP value, delete the object pointed to by the AP and bind the AP to the P

AP. Release ()

Returns the pointer saved by the AP and makes the AP unbound.

AP. Get ()

Returns the pointer saved by the AP.

Auto_ptr can only be used to manage one object returned from new. It cannot manage dynamically allocated arrays. When auto_ptr is copied or assigned a value, auto_ptr cannot be stored in the standard library container class.

3. Each auto_ptr object is bound to an object or points to an object. When the auto_ptr object points to an object, it can be said that it "owns" the object. When the auto_ptr object exceeds the scope or is revoked separately, the dynamic allocation object pointed to by auto_ptr is automatically reclaimed.

Auto_ptr is a template that can save any type of pointer.

Example

View sourceprint?
void f()  {      auto_ptr<int> ap(newint(42)); // allocate a new object      // code that throws an exception that is not caught inside f }   // auto_ptr freed automatically when function ends 

4. Note that the constructor that accepts pointers is an explicit constructor. Therefore, you must create an auto_ptr object in the form of initialization.

Example

View sourceprint?
// error: constructor that takes a pointer is explicit and can't be used implicitly auto_ptr<int> pi = new int(1024);  auto_ptr<int> pi(new int(1024)); // ok: uses direct initialization 

The object created by the new expression specified by PI is automatically deleted when it exceeds the scope.

5. The main purpose of auto_ptr is to ensure that the objects referenced by the auto_ptr object are automatically deleted, while common pointer actions are supported.

Example

View sourceprint?
auto_ptr<string> ap1(new string("Hellobaby!")); *ap1 = "TRex"; // assigns a new value to the object to which ap1 points string s = *ap1; // initializes s as a copy of the object to which ap1 points if (ap1->empty()) // runs empty on the string to which ap1 points 

6. Assigning and copying auto_ptr objects are destructive operations, which are different from copying and assigning common pointers. After a normal pointer is assigned or copied, the last two pointers direct to the same object. After the auto_ptr object is copied or assigned, the ownership of the basic object is transferred from the original auto_ptr object to the copy, the original auto_ptr object is reset to the unbound state.

Therefore, the left and right operands of auto_ptr values must be modifiable left values. Because the standard library container requires that the two objects after copying or assigning values are equal, auto_ptr cannot be stored in the standard container.

7. By default, the internal pointer value of auto_ptr is set to 0.

8. Test the auto_ptr object

The auto_ptr type does not define the type conversion that can be used as a condition. On the contrary, to test the auto_ptr object, you must use its get Member, which returns the base pointer contained in the auto_ptr object.

Example

View sourceprint?
// error: cannot use an auto_ptr as a condition  if (p_auto)     *p_auto = 1024;  // revised test to guarantee p_auto refers to an object  if (p_auto.get())     *p_auto = 1024; 

You should only use get to query the auto_ptr object or use the returned pointer value. You cannot use get as the real parameter for creating other auto_ptr objects.

9. Reset operations

You cannot directly assign an address (or other pointer) to an auto_ptr object.

Example

View sourceprint?
#include <iostream>  #include "memory"  using namespace std;     int main()  {      auto_ptr<int> p_auto(newint(123));      //p_auto = new int(1024); // error: cannot assign a pointer to an auto_ptr     if (p_auto.get())          *p_auto = 1024;      else         p_auto.reset(new int(1042));     return 1;  } 

Just as its own assignment has no effect, if the reset function of the same pointer already saved in the auto_ptr object is called, it will not work and the object will not be deleted.

10. correct use of the auto_ptr class has the following restrictions:

1) do not use the auto_ptr object to save the pointer to the static allocation object. Otherwise, when the auto_ptr object itself is revoked, it will try to delete the pointer to the non-dynamic allocation object, leading to undefined behaviors.

2) Never use two auto_ptrs objects to point to the same object. One obvious cause of this error is to use the same pointer to initialize or reset two different auto_ptr objects. Another subtle way to cause this error is to use the get function of an auto_ptr object to initialize or reset another auto_ptr object.

3) do not use the auto_ptr object to save the pointer pointing to the dynamically allocated array. When an auto_ptr object is deleted, it only releases one object-it uses the common delete operator instead of the Delete [] operator of the array.

4) do not store auto_ptr objects in containers. The container requires that the stored types define the copy and value assignment operators so that they are similar to built-in type operators: After copying (or assigning values), the two objects must have the same value, the auto_ptr class does not meet this requirement.

11. exception description

1) Definition

Example

View sourceprint?
Void recoup (INT) Throw (runtime_error); void no_problem () Throw (); // The empty description list indicates that the function does not throw any exception

Exception description is part of the function interface. The function definition and any declaration of the function must have the same exception description. If no exception is specified in the function declaration, the function can throw any type of exception.

2) The exception description of the virtual function of the base class can be different from the exception description of the corresponding virtual function in the derived class, but the exception description of the virtual function of the derived class should be stricter. In the base class, the exception list of the virtual function is the superset of the exception list of the derived class.

12. exception description can be provided in the definition of function pointers. When another pointer is used to initialize a pointer to a function with an exception description, or the latter is assigned to the function address, the exception description of the two pointers does not need to be the same. However, the exception of the source pointer must be at least as strict as that of the target pointer.

Example

View sourceprint?
void recoup(int) throw(runtime_error); // ok: recoup is as restrictive as pf1  void (*pf1)(int) throw(runtime_error) = recoup; // ok: recoup is more restrictive than pf2  void (*pf2)(int) throw(runtime_error, logic_error) = recoup; // error: recoup is less restrictive than pf3  void (*pf3)(int) throw() = recoup; // ok: recoup is more restrictive than pf4  void (*pf4)(int) = recoup; 

Reference

[1]

Http://www.cnblogs.com/mydomain/archive/2011/04/14/2016565.html

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.