Auto_ptr of C + + smart pointers

Source: Internet
Author: User

1. Auto_ptr
Auto_ptr is the class template provided by the C + + standard library, which is the owner of this memory, and the Auto_ptr object is initialized to the dynamic memory created by new, and a piece of memory cannot be assigned to two owners at the same time. When the Auto_ptr object life cycle ends, its destructor automatically frees the dynamic memory owned by the Auto_ptr object. Even if an exception occurs, dynamic memory can be freed by the exception stack unwind process. Auto_ptr does not support the new array.
2. auto_ptr need to include header files
#include <memory>

3. Methods for initializing Auto_ptr objects

1) constructor function
1] Constructs an existing normal pointer to dynamic memory as a parameter
int* p = new int (33);
Auto_ptr<int> API (p);

2] Direct construction of smart pointers
auto_ptr< int > API (new int (33));

2) Copy Construction
Constructs a new smart pointer with an existing smart pointer
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
auto_ptr< string > Pstr_auto2 (Pstr_auto); Using Pstr_auto to construct Pstr_auto2
Because a piece of dynamic memory intelligence is exclusively enjoyed by a smart pointer,The process of ownership transfer occurs when a copy is constructed or assigned。 During this copy construction, Pstr_auto loses ownership of the string memory, and Pstr_auto2 obtains it, and Pstr_auto2 is responsible for the automatic destruction of the memory when the object is destroyed.

3) Assign Value
Constructs a new smart pointer with an existing smart pointer
auto_ptr< int > p1 (new int (1024));
auto_ptr< int > p2 (new int (2048));
P1 = p2;

The object pointed to by P1 is deleted before the assignment. After assignment, P1 has ownership of the int type object. The object value is 2048. P2 is no longer used to point to the object.

4. The Empty auto_ptr
The usual pointer, when defined, does not point to any object, and we use NULL to assign it a value. For smart pointers, since the constructor has a default value of 0, we can directly define the empty auto_ptr as follows:
auto_ptr< int > p_auto_int; Do not point to any object

5.prevents two Auto_ptr objects from owning the same object(A piece of memory)
Because the ownership of AUTO_PTR is unique, the following code can cause confusion.

int* p = new int (0);
Auto_ptr<int> AP1 (P);
Auto_ptr<int> AP2 (P);

Because AP1 and AP2 both think that the pointer p is the tube, in the destruction attempt to delete P, two times the behavior of deleting the same object is undefined in the C + + standard, so we must prevent the use of auto_ptr.

6. Beware of smart pointers as parameters
1) when passed by value, a local object is generated in the function's scope during the function call to receive the incoming auto_ptr (copy construct), so thatThe passed-in argument Auto_ptr loses its ownership of the original object, and the object is deleted locally auto_ptr when the function exits. The following example:
void F (auto_ptr<int> AP)
{Cout<<*ap;}
Auto_ptr<int> AP1 (new int (0));
f (AP1);
cout<<*ap1; Error, after the F (AP1) function call, AP1 no longer owns any objects.

2) when referencing or pointers, the above copy process does not exist. However, we do not know what to do with the incoming auto_ptr in the function, and if some of these operations cause it to lose ownership of the object, this could lead to a fatal execution-time error.
Conclusion:The const reference is the bottom line where smart pointers are passed as parameters

7.Auto_ptr cannot initialize to point to non-dynamic memory
The reason is simple, and the delete expression is applied on pointers that are not dynamically allocated, which results in undefined program behavior.

8. member functions commonly used by auto_ptr
1) Get ()
Returns the memory address of the object that auto_ptr points to. The following example:
int* p = new int (33);
cout << "The Adress of P:" << p << Endl;
Auto_ptr<int> AP1 (P);
cout << "The Adress of Ap1:" << &ap1 << Endl;
cout << "The Adress of the object which AP1 point to:" << ap1.get () << Endl;
The output is as follows:
The Adress of p:00481e00
The Adress of ap1:0012ff68
The adress of the object which AP1 point to:00481e00
The first line is the same as the third row, which is the address of the memory where int resides. The second line is the address of the memory where the class object itself is AP1.

2) Reset ()
Re-sets the object that auto_ptr points to. is similar to an assignment operation, but the assignment operation does not allow a normal pointer to be assigned directly to Auto_ptr, and reset () allows. The following example:
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
Pstr_auto.reset (New string ("Long-neck"));
In the example,before resetting the Pstr_auto has the "Brontosaurus" character memory ownership, this memory will be released first。 The Pstr_auto then has the ownership of the "Long-neck" character memory.
Note:Reset (0) can release objects, destroy memory。

3) Release ()
returns the memory address of the object that auto_ptr points to, and frees ownership of the object.
Initializing auto_ptr with this function avoids the case of having the same object for two Auto_ptr objects (as opposed to the Get function).
Examples are as follows:
auto_ptr< string > Pstr_auto (New String ("Brontosaurus"));
auto_ptr< string > Pstr_auto2 (Pstr_auto.get ()); This is two auto_ptr have the same object,undefined behavior occurs when an object is disposed
auto_ptr< string > Pstr_auto2 (Pstr_auto.release ()); Release can first free up ownership

Example
#include <iostream> #include <memory>using namespace std;struct a{        explicit A (String str) {m_str = str; cout << m_str << ": constructor~~" << Endl; }        ~a () {cout << m_str << ": deconstructor~~~" << Endl;}        void Outmsg () {cout << "outmsg:" +m_str << Endl;}        Private:        string m_str;}; int main () {        auto_ptr<a> aptr (New A (String ("Auto"));        Aptr.get ()->outmsg ();        Aptr.reset (New A (String ("MSG"));        Auto_ptr<a> aptr2 (Aptr.release ());        Auto_ptr<a> aptr2 (Aptr.get ());  A segment error occurred because Aptr and APTR2 pointed to the same object and there was a recurring issue with double free  or corruption (fasttop)}

Execution Result: auto:constructor~~
Outmsg:auto
msg:constructor~~
auto:deconstructor~~~
msg:deconstructor~~~

Auto_ptr of C + + smart pointers

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.