About Std:auto_ptr std:shared_ptr std:unique_ptr

Source: Internet
Author: User

Many people have heard of the standard auto_ptr smart pointer mechanism, but not everyone uses it every day. This is really a pity, because auto_ptr gracefully solves the common problems in C + + design and coding, and using it correctly can generate robust code. This article explains how to use auto_ptr correctly to make your code more secure-and how to avoid dangerous but common misuse of auto_ptr, which can cause intermittent seizures and difficult to diagnose bugs.

1. Why is it called an "automatic" pointer?
Auto_ptr is just one of many possible smart pointers. Many business libraries offer more sophisticated smart pointers, which are versatile and amazing, from managing the number of references to providing advanced proxy services. The standard C + + auto_ptr can be regarded as a smart pointer to the Ford Escort (Elmar Note: may refer to a Ford's home-compatible model): A simple, universal smart pointer, it does not contain all the small tricks, not like a dedicated or high-performance smart pointer so luxurious, But it can do a lot of common work well and it's good for everyday use.

What Auto_ptr does is to dynamically allocate objects and automatically perform cleanup when the object is no longer needed. Here is a simple code example that does not use auto_ptr so it is unsafe:
Example 1 (a): Original code
//
void F ()
{
t* pt (New T);

/*... More code ... */

Delete pt;
}

Most of us write similar code every day. If the F () function has only three rows and there are no surprises, it might be nice to do so. However, if f () never executes the DELETE statement, either because it was prematurely returned, or because an exception was thrown when the function body was executed, the allocated object was not deleted, resulting in a classic memory leak.

An easy way to make Example 1 (a) secure is to encapsulate the pointer in a "smart" pointer-like object that has this pointer and can automatically delete the object that the pointer refers to when it is refactored. Because this smart pointer can be as simple as an automatic object (that is, it is automatically destroyed when it is scoped), it is naturally referred to as the "smart" pointer:

Example 1 (b): Security code, using Auto_ptr
//
void F ()
{
Auto_ptr<t> pt (New T);

/*... More code ... */

}//Cool: The destructor is called when the PT is out of scope,
So the object is automatically deleted

The code now does not leak objects of type T, whether the function exits gracefully or throws an exception, because the PT destructor is always called at the time of the stack. The cleanup will be done automatically.

Finally, using a auto_ptr is as easy as using a built-in pointer, and if you want to "undo" the Resource and take the manual ownership again, we just call release ():

Example 2: Using a auto_ptr
//
void G ()
{
t* pt1 = new T;
Now, we have a well-distributed object.

Passed ownership to a Auto_ptr object
Auto_ptr<t> pt2 (PT1);

Use auto_ptr just like we used to use a simple pointer
*pt2 = 12; Just like "*pt1 = 12;"
Pt2->somefunc (); Just like "Pt1->somefunc ();"

Use Get () to get the value of the pointer
ASSERT (Pt1 = = Pt2.get ());

Use release () to revoke ownership
t* PT3 = Pt2.release ();

Delete this object yourself, because now
No auto_ptr owns this object.
Delete Pt3;

}//Pt2 no longer has any pointers, so do not
Try to delete it ... ok, do not repeat delete

Finally, we can use Auto_ptr's reset () function to reset the auto_ptr to have another object. If the auto_ptr already has an object, it will first delete the object already owned, so calling Reset () is like destroying the auto_ptr, and then creating a new one and owning the object:

Example 3: Using Reset ()
//
void H ()
{
Auto_ptr<t> pt (New T (1));

Pt.reset (New T (2));
Delete the first t assigned by "New T (1)"

}//Finally, the PT is out of scope,
The second t was also deleted.

correct use of std::auto_ptr

1, Auto_ptr class

Auto_ptr is a template class that is defined as follows:

Template <typename Type>
Class
Auto_ptr {...} ;

It stores a pointer to type.

As the name implies, Auto_ptr is a smart pointer that contains a pointer to a dynamically allocated memory and destroys the memory pointed to by the containing pointer at the end of its life cycle.

Example 1:

void F ()

{

type* pt (new Type);

Some code ...

Delete pt;
}

Such code is common, but it can cause a memory leak. First you use new, you have to remember to use Delete, but even if you remember to use Delete, there will be problems. If f () throws an exception before executing the delete PT, the function returns. Then the assigned object is not deleted.

With auto_ptr, these problems are solved gracefully.

Example 2:

void F ()

{

Auto_ptr<type> pt (new Type);

Some code ...
}

Now the code does not reveal the type of the object. Whether the function ends normally or throws an exception, the PT destructor is called to delete the allocated object.

2, Auto_ptr constructor

Constructor 1:explicit auto_ptr (type* _ptr = 0) throw();

auto_ptr<int> pt; A pointer containing a int* and initialized to null

auto_ptr<int> pt (new int(123)); Contains a pointer to a int* and initializes the address to 123

auto_ptr<int> pt = new int(123); The error! constructor is declared as explicit

Constructor 2:auto_ptr (auto_ptr<type>& _right) throw();

int* ptr = new int();

auto_ptr<int> Pt1 (PTR); Constructor 1

auto_ptr<int> pt2 (PT1); Transfer the use of PT1 to pt2, note that pt1 points to null.

PT1 calls its own release () function, passing the internal pointer address to PT2

Constructor 3:template<TypeName other>

Auto_ptr (auto_ptr<other>& _right) throw();

The purpose of declaring such a copy constructor is to have a pointer to a derived class that can be converted to a base class.

Cases:

class Base {};

class Derived: public Base {};

Auto_ptr<derived> pderived (new Derived);

Auto_ptr<base> pbase (pderived); So that the code can pass the compiler

The essence of this is to let the derived* within the Auto_ptr class convert to base*

Constructor 4:auto_ptr (auto_ptr_ref<type> _right) throw();

Temporary brief

3, AUTO_PTR member function

member function 1: Type* get () const throw();

Get the address that contains the pointer

int* ptr = new int (123);

Auto_ptr<int> pt (PTR);

ASSERT (pt.get () = = ptr); Equal, pointing to the same address

member function 2: type* release () throw();

Returns the address containing the pointer and sets the containing pointer to null

string* pstr = new string ("Hello");

Auto_ptr<string> pt (PSTR);

Pt.release (); Does not point to a string object

At this point, pt.get () equals null

Delete pstr; You should manually delete the block of memory that pstr points to

member function 3:void Reset (type* _ptr = 0);

double* pdouble1 = new double (3.14);

double* pdouble2 = new double (1.23);

Auto_ptr<double> pt1 (PDOUBLE1);

Pt1.reset (Pdouble2); The block of memory that pt1 points to will be deleted is the one that pdouble1 points to.

At this point, Pt.get () equals pdouble2

cout << *pdouble1; Error,pdouble is already a wild pointer.

4, Summary of Use

The 1,auto_ptr stored pointer should be null or point to a dynamically allocated block of memory.

2,auto_ptr stored pointers should point to a single object (new, not new[).

3, two Auto_ptr objects do not point to the same block of memory at the same time. Understand what happens when you assign a value of 2 auto_ptr objects.

4, do not put the Auto_ptr object in the container.

5, when Auto_ptr is used as a function parameter, it is best to declare the const auto_ptr<t>& (by const REF). When the function return value can be simply passed (by value).

shared_ptr

Unique_ptr

About Std:auto_ptr std:shared_ptr std:unique_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.