C + + security Exception std:auto_ptr

Source: Internet
Author: User

Auto_ptr it is the C + + standard library (<utility>) for a smart pointer class template to address the problem provided by resource leaks (note: This is just a simple smart pointer)
Auto_ptr in the realization of the principle of fact raii, access to resources in the construction time. When the resource is freed, the destructor, and the associated pointer operation is overloaded. Use it like a normal pointer.


Std::auto_ptr<classa> PA (new ClassA);

A lot of people have heard of the standard auto_ptr smart pointer mechanism, but not everyone uses it every day. That's a pity. Because auto_ptr gracefully overcomes the common problems in C + + design and coding, it is possible to use it correctly to generate robust code. This article explains how to use auto_ptr correctly to make your code more secure-and how to avoid auto_ptr critical but common misuse that can cause intermittent seizures and difficult to diagnose bugs.

1. Why call it "self-active" pointer?
Auto_ptr is just one of many possible smart pointers. Many business libraries provide more sophisticated smart pointers. Versatile and amazing, from managing the number of references to providing advanced proxy services. Ford Escort, who can think of the standard C + + auto_ptr as a smart pointer (Elmar Note: Probably a Ford's home-fit model): A simple, versatile smart pointer that doesn't include all the tips. It's not as extravagant as a dedicated or high-performance smart pointer. But it can be very good to complete a lot of common work, it is very suitable for the daily use of the.

What Auto_ptr does is to dynamically allocate objects and run cleanup on their own when the object is no longer needed. Here is a simple code demo sample that does not use auto_ptr so it is unsafe:
Demo Sample 1 (a): Original code
//
void F ()
{
t* pt (New T);


/*... A lot of other code ... * *


Delete pt;
}


Most of us write similar code every day.

Assuming that the F () function has only three rows and that there are no surprises, it might be nice to do so.

But suppose F () never runs the DELETE statement. Or because of premature return. Or because an exception was thrown when the function body was run, the allocated object was not deleted. Thus we produce a classic memory leak.


The simple way to make demo Example 1 (a) secure is to encapsulate the pointer in a "smart" pointer-like object that has this pointer and can delete the object it refers to when it is refactored. Because this smart pointer can be as simple as a self-active object (that is, it out of scope, it will voluntarily destroy). So it's very natural to call it the "smart" pointer:


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


/*... A lot of other code ... * *


}//Cool: The destructor is called when the PT is out of scope.
So the object is voluntarily deleted by itself


The code now does not leak objects of type T. Whether the function exits gracefully or throws an exception. Since the PT destructor is always called when it is out of the stack. The cleanup will take its own initiative.


Finally, using a auto_ptr is as easy as using a built-in pointer. And assuming that you want to "undo" the resources, and once again take the full power of manual, we just call release ():


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


Pass the whole right 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 all rights
t* PT3 = Pt2.release ();


Delete this object by itself, because now
No matter what auto_ptr owns this object
Delete Pt3;


}//Pt2 no longer have any pointers, so do not
Try to delete it ... ok. Do not delete repeatedly


Finally, we can use the Reset () function of auto_ptr to reset auto_ptr so that it has an object. Suppose the auto_ptr already has an object. Then, it deletes the object already owned, so calling Reset () is like destroying the auto_ptr, and then creating a new one and owning the object:


Demo 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)"


}//Last. The PT is out of scope.
The second t was also deleted.


2. Here are a few important points to note about Auto_ptr:

1,transfer of Ownership

Auto_ptr Unlike the share_ptr in the Boost library, AUTO_PTR does not consider reference counts, so an object can be owned by only one auto_ptr, which transfers such ownership when assigned to other auto_ptr.

#include <utility> #include <iostream>using namespace std; Class A{public:    A () {id = ++count; cout << "Create A" << ID  <<  "\ n";}    ~a () {cout << "destroy A" << ID << "\ n";} Private:    static int count;    int id;}; int a::count = 0; /* Call this function to lose all rights */void sink (auto_ptr<a> A) {    cout << "Enter sink () \ n";}/* Call the function to create the object and get all rights */auto_ptr <A> Create () {    cout << "Enter create () \ n";    Auto_ptr<a> A (new A ());    return A;} int main (int argc, char *argv[]) {    auto_ptr<a> a1 = Create ();    auto_ptr<a> A2 = A1; /* Transfer All rights, at this time A1 invalid *    /auto_ptr<a> A3 (New A ());    cout << "Exit create () \ n";    Sink (A2);/* Lose All rights, you will find the release of A2 in the sink function *    /cout << "Exit sink () \ n";    return 0;}



The output is: <br>enter Create () <br>create a1<br>create a2<br>exit Create () <br>enter sink () <br>destroy a1<br>exit Sink () <br>destroy a2<br><br>
2. From the above, because in the assignment. The full weight is transferred when the parameter is passed, so do not do so easily.


For example:std::auto_ptr<classa> PA (New ClassA ());


Bad_print (PA); Lost all rights.


pa->...; Error

How do you prevent a function call from transferring all rights?

In the page43 of the C + + standard library, it is mentioned that the use of const reference, such a form of participation will not surrender all rights. Due to the inability to make const reference all right!!

3, use auto_ptr as the member variable to avoid resource leaks.


To prevent resource leaks. We usually apply in the constructor, and the destructor is freed. However, only a constructor call succeeds, the destructor is called, in other words, if an exception is generated in the constructor, the destructor will not be called. This will cause a potential resource leak.




For example, suppose that the class has 2 member variables, pointing to two resources. The constructor failed when the request for resource a succeeded in the constructor, but the request for resource B failed. Then the destructor is not called. Then resource a leaks.




To solve this problem, we can use auto_ptr instead of the normal pointer as a member variable, so that the constructor that calls the successful member variable will definitely call its destructor, then it can avoid the problem of resource leakage.


4, do not misuse auto_ptr


1) auto_ptr cannot share all rights, that is, do not let two auto_ptr point to the same object.




2) Auto_ptr cannot point to an array. Since auto_ptr is simply calling delete at the time of the destructor, the array should be called delete[].




3) Auto_ptr is just a simple smart pointer. If you have special needs. You need to use other smart pointers, such as share_ptr.


4) Auto_ptr cannot be used as a container object, and the elements in the STL container often have to support copying. Assignment, Auto_ptr will pass all the right in the process. Then the source and sink elements are not equivalent.

References:

1 http://www.cnblogs.com/qytan36/archive/2010/06/28/1766555.html

2 http://blog.csdn.net/cyblueboy83/article/details/1792463

3 C + + primer page591~

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C + + security Exception std:auto_ptr

Related Article

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.