"C + +" smart pointer (smart Pointer)

Source: Internet
Author: User

1. Problems with traditional pointers

There are many problems with traditional pointers, such as the life cycle of the object to which the pointer is pointing, the suspend reference (dangling references), and the memory leaks.
The following is a procedure for using a traditional pointer

void Foo() {    int *iPtr = new int[5];    // manipulate the memory block    ...    ...    ...    delete[] iPtr;}

The above code will run normally and the memory will be properly freed, but using pointers often happens in unexpected situations, such as accessing an illegal memory unit, with the exception of 0 operations, and returning return statements processed according to some criteria.

2. What is a smart pointer (smart Pointer)

Smart pointers are RAII (Resource acquisition is initialization) used to dynamically allocate memory. It provides all the interfaces of a normal pointer plus a few exception handling. During the construction phase, it allocates memory and automatically frees the occupied memory within its scope.
In c++98, use auto_ptr to solve the above problem.

2.1 auto_ptr
#include <iostream>#include <memory>using namespace STD;classTest { Public: Test (intA =0): M_a (a) {} ~test () {cout<<"Calling destructor"<< Endl; } Public:intM_a;};intMain () {auto_ptr<Test> P (NewTest (5));cout<< p->m_a << Endl;return 0;}

Output Result:

The code above will intelligently release the associated memory.

#include <iostream>#include <memory>using namespace STD;classTest { Public: Test (intA =0): M_a (a) {} ~test () {cout<<"Calling destructor"<< Endl; } Public:intM_a;};voidFun () {intA =0, B =5Cif(A = =0) {Throw "Invalid Divisor"; } c = b/a;return;}intMain () {Try{auto_ptr<Test> P (NewTest (5)); Fun ();cout<< p->m_a << Endl; }Catch(...) {cout<<"Something has gone wrong"<< Endl; }return 0;}

In the above code, even if an exception is thrown, the pointer is normally released. This is because when the exception is thrown, the stack is untied (stack unwinding). When all belonging try block local objects are destroyed, the pointer p is not in scope and is freed.

Question 1.

At least for the moment auto_ptr it's smart. But it has a very fundamental drawback: auto_ptr it passes its own ownership when it is assigned to another auto_ptr object. as shown in the following procedure, auto_ptr when an object is passed to an object in a function, Fun() auto_ptr its ownership, or smartness, will no longer return to auto_ptr the P pointed to by the original.

#include <iostream>#include <memory>using namespace STD;classTest { Public: Test (intA =0): M_a (a) {} ~test () {cout<<"Calling destructor"<< Endl; } Public:intM_a;};voidFun (auto_ptr<Test> p1) {cout<< p1->m_a << Endl;cout<<"Fun () End"<< Endl;}intMain () {auto_ptr<Test> P (NewTest (5)); Fun (p);cout<< p->m_a << Endl;return 0;}

Operation Result:

The above program will crash because of the presence of wild pointers auto_ptr . The main reason for the above-mentioned code collapse is that the original p possession of its own allocation of memory management. However, Fun() its management is transferred through a function, at which point p1 p1 the block of memory it points to will be released at the end of the smartness. At this point, the original p will have any memory, resulting in the access to a null pointer, the reference problem of the wild pointer.

Question 2.

auto_ptr cannot be used on array objects . This means that you cannot use the operator new[] .

int main(){    auto_ptr<Test> p(new Test[5]);    return0;}

The code above will be runtime error. Because for the auto_ptr purposes of that, it is called delete rather than delete [] .

Question 3.

auto_ptr cannot be used in some standard container libraries . For example vector , list and map so on.

C++11 proposed a new kind of smart pointer, and all gave its corresponding intention.

2.2 shared_ptr

Not to be continued ...

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"C + +" smart pointer (smart Pointer)

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.