Go Smart pointers in the C++11

Source: Internet
Author: User

1. Std::auto_ptr Some of the concepts that violate C + + programming. It has been "not recommended".
2. The following is transferred from: http://blog.csdn.net/lanergaming/article/details/24273419

There is an automatic garbage collection mechanism in C # and Java, where the. NET runtime and Java virtual machines can manage allocated heap memory and are automatically reclaimed when objects lose references, so in C # and JVA,
Memory management is not a big problem. The C + + language has no garbage collection mechanism and must release allocated heap memory on its own, otherwise it will leak memory.
I believe most C + + developers have experienced memory leaks, and the problem of finding memory leaks often takes a lot of effort. To solve this troublesome problem, you can
To take some measures, the most effective way is to use smart pointers! Using a smart pointer does not worry about memory leaks, because smart pointers can automatically delete deleted points
With the memory.

A smart pointer is a pointer to a dynamically allocated (heap) object that is used for lifetime control to ensure that dynamically allocated objects are destroyed automatically and correctly to prevent memory
Leaked. One of its common implementation techniques is the use of reference counting. Each time it is used, the internal reference count is added 1, each time it is refactored, the internal reference count is reduced by 1, minus 0 o'clock, and the
In addition to the heap memory pointed to.

Prior to c++11, C + + had no built-in smart pointers, which could have been preceded by boost's smart pointers or by inventing the wheels themselves. C++11 now built-in smart pointers so that we can
It's handy to use smart pointers. The smart pointers in c++11 include:

    • Std::shared_ptr
    • Std::unique_ptr
    • Std::weak_ptr

Std::shared_ptr

Std::shared_ptr uses reference counting. Each shared_ptr copy points to the same memory. When the last shared_ptr is destroyed, the memory will be released
Put
Let's see how shared_ptr use it.
1. Initialization

The initialization of the smart pointer std::shared_ptr<int> p (new int (2));std::shared_ptr<int> P2 = p;std::shared_ptr< baseconnector> m_connt = make_shared<connector> (M_ios, M_strip, M_port);

The smart pointer is initialized by a constructor, assignment function, or make_shared function.
Smart pointer initialization lets you specify a delete

void Deleteintptr (int* p) {delete p;} Std::shared_ptr<int> p (new int, deleteintptr);p a reference count of 0 will automatically invoke the delete deleteintptr

2. The original pointer in the smart pointer, obtained through get
char* pData = Pbuf.get ();

3. Precautions. Although the smart pointer can automatically manage heap memory, it has a number of pitfalls that need to be noted when using:

1. Do not give a native pointer to multiple shared_ptr management

int* ptr = new int;shared_ptr<int> P1 (PTR);shared_ptr<int> p2 (PTR); Logic error causes PTR to be deleted two times

2. Do not give the this pointer to shared_ptr
3. Do not create shared_ptr in function arguments

Function (shared_ptr<int> (new int), g ()); Have defects
The possible process is first new int, then g (), G () exception,shared_ptr<int> not created, int memory leak
Shared_ptr<int> p (new int ());
F (P, g ());
4. The shared_ptr of this object is generated internally

The Enable_shared_from_this class, in which the member function Shared_from_this () is determined and returns shared_ptr<t>. This function can only be used after the Shared_ptr<t> constructor is called. The reason is that enable_shared_from_this::weak_ptr is not set in the constructor (the constructor here refers to the constructor of type T), but rather is set in the constructor of the Shared_ptr<t> (the constructor here refers to the type The Shared_ptr<t> constructor).

If the shared_from_this () member function is not used, the this pointer is constructed with a shared_ptr, and the shared_ptr of the object itself is managed by this resource, and two destructors occur during the destruction;

Class Y:public std::enable_shared_from_this<y>{boost::shared_ptr<y> getself () {return shared_from_this ( );}}; Boost::shared_ptr<y> Spy (New Y) boost::shared_ptr<y> p = spy->getself (); Ok

5.shared_ptr as a member of an object, be careful that the resource cannot be freed because of a circular reference.

struct a;struct b;struct a{std::shared_ptr<b> m_b;}; struct b{std::shared_ptr<a> m_a;}; Std::shared_ptr<a> PtrA (new A);std::shared_ptr<b> ptrb (new B);p Tra->m_b = Ptrb;ptrb->m_a = PtrA;

Ptra and PTRB reference each other, leaving the scope with a reference count of 1, resulting in memory not being freed, the solution is to change the member variable of either a and B to weak_ptr
The solution is to change the member variable of either a and B to weak_ptr

struct B
{
Std::weak_ptr<a> M_a;
};

Ptrb->m_a does not increase the reference count of the A object, so a reference count of 0,m_b is reduced by one when the A object leaves scope, and the reference count is reduced from 1 to 0 after leaving scope.

Std::weak_ptr
A weak reference pointer that is used to monitor smart pointers without adding 1 to the reference count. You must first convert to Std::shared_ptr before accessing the referenced object.

A concept used to express temporary ownership: When an object needs to be accessed only when it is present and may be deleted by others at any time, you can use

To track the object. When temporary ownership is required, it is converted to std::shared_ptr, and if the original Std::shared_ptr is destroyed, the lifetime of the object will be extended until the temporary std::shared_ptr is destroyed as well.

It can also be used to avoid std::shared_ptr circular references.

Std::weak_ptr<int> GW; void F () {if (Auto SPT = Gw.lock ()) {//have to is copied into a shared_ptr before usagestd::cout << *spt << "\ n ";} else {std::cout << "GW is expired\n";}} int main () {{Auto SP = std::make_shared<int>; GW = Sp;f ();} f ();} Output GW is expired
Std::unique_ptr
Unique_ptr does not share its pointer. It cannot be copied to another unique_ptr, Unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to the new Unique_ptr and the original Unique_ptr no longer owns it.
int* p = new int;std::unique_ptr<int> ptr (p);std::unique_ptr<int> ptr1 = ptr; Cannot copy, compile error auto PTR2 = Std::move (PTR); Transfer ownership, now PTR that block of memory is PTR2 all, PTR2 becomes invalid pointer.

The smart pointer is a good thing, and after using it there is no need to worry about memory release, memory leaks, my project is a smart pointer, no delete.

Smart pointers make our programs more secure, except that circular references lead to memory leaks, and others are safe and can be used with confidence.

Go Smart pointers in the C++11

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.