C++11 Smart pointer

Source: Internet
Author: User

Objective

The recent period of time to look at the code, the use of C + + smart pointers, found that they can not understand the code in the expression of what meaning, so dedicated to take a time to make up their own this lack of knowledge.
Reference book "in-depth application c++11: Code Optimization and Engineering Application"

Smart pointers

The C++11 provides 3 smart pointers:

    • Std::shared_ptr,
    • Std::uniq_ptr
    • Std::weak_ptr

Need to reference header file when using#include <memory>

Std::shared_ptr

Std::share_ptr uses a reference count, each shared_ptr copy points to the same memory, and the last time the shared_ptr is refactored, the memory is freed.

1 Basic usage of share_ptr
    • Smart pointer Initialization and assignment

      A normal pointer is not allowed to be assigned to a smart pointer, because a smart pointer is a class, and a normal pointer is a value

    • For a pointer that is not initialized, you can use reset to complete the initialization.

    • Smart pointers are overloaded with the bool type operator, so you can use smart pointers directly to determine if an empty
2 Getting the raw pointer

The original pointer p.get() can be used to get the smart pointer, cout can also directly output the original pointer.

The normal pointer can be directly equal to the pointer data of the original pointer get ()

3, specify the Remove device

Smart pointer initialization lets you specify a delete

You can use lambda expressions to simplify the wording of a delete

When you use smart pointers to manage arrays, you need to use a std::share_ptr because the release of array objects is not supported

You can also use the default delete, std::d efault_delete

Can't use Default_delete in VC + +

std::shared_ptr<int> p(new int[10], std::default_delete<int[]>);
4. Precautions for using shared_ptr
    1. Do not initialize multiple shared_ptr with a raw pointer, because it causes two destruction, as follows:

      Using the vc++2015 test found that creating multiple smart pointers with the original pointer generates an error
      !
      There is no problem with using smart pointers to initialize multiple smart pointers, because smart pointers are all included in the counting system

    2. Do not create shared_ptr in function arguments. Because the order of the function parameters of C + + is different under different compilers. The right thing to do is to create it first and then pass in

//错误示范function(shared_ptr<int>(new int), g());
    1. Returns the This pointer by Shared_from_this ().

      The this pointer returned by SP1 is used as a bare pointer, SP2 gets the pointer and becomes a smart pointer unrelated to SP1. Two smart pointers are refactored after the declaration period ends, resulting in a repetitive destructor operation

      A smart pointer cannot return the this pointer directly, it needs to std::enable_shared_from_this return a smart pointer by its method through a derived class shared_frome_this() .

    2. Avoid cyclic use. The biggest flaw of a smart pointer is a circular reference, which causes two pointers to not be refactored.

      When two smart pointers refer to each other, the count is 2, so at the end, the condition of the destruction is not reached, so none of them will be destructor

Std::unique_ptr

Exclusive smart pointer, which does not allow other functional pointers to share its internal pointers, and does not allow assignment of one unique_ptr to another unique_ptr

    unique_ptr<int> myPtr(new int(1));    //下面的代码是错误的,无法通过=进行复制    unique_ptr<int> myPtr2 = myPtr;

Unique_ptr Although it can not be copied, but can be transferred, through the std::move to transfer to other UNIQUE_PTR

You can see how unique_ptr moves the contents of the pointer by moving it.

    //unique_ptr只可以move不可以复制    unique_ptr<MyType> other_p2 = other_p;

The use of shared_ptr and uunique_ptr, depending on the actual application to choose, if you only want to have a smart pointer to manage resources or to manage the array with unique_ptr, if you want to have more than one pointer to manage the same resource, use shared_ptr

weak_ptr Weak reference Smart pointer
    • The weak reference pointer weak_ptr is used to monitor shared_ptr. The main purpose is to monitor the shared_ptr declaration cycle.
    • The resource cannot be manipulated because WEAK_PTR does not have overloaded operators * and.
    • Its construction does not increase the reference count, and its destruction does not reduce the reference count, but is used to monitor the existence of resources managed in the shared_ptr.
    • Weak_ptr can also be used to return the this pointer and solve the problem of circular references
WEAK_PTR Basic Usage
    • use_cout()to get the reference count for the current watch resource
    • expired()to get a valid
    • By lock means of the method to obtain the monitored shared_ptr
      • The contents of the pointer can be accessed after lock
      • weak_ptr can be monitored directly by assigning a value
Manage memory allocated by third-party libraries with smart pointers

Smart pointers are used when invoking third-party interface libraries, and because the third-party library returns pointers are generally raw pointers, using smart pointers can be invoked in the event of an error execution

void* p = GetHandle()->Create();std::shared_ptr<void> sp(p, [this](void*p){GetHandle()->Release(p);});
Summarize
    • SHARE_PTR replication increases the count, each copy increases, and only the last time it is released is the real delete pointer.
    • shared_ptr and uniqi_ptr How to choose: if there is only one pointer to manage a resource or manage an array, you can use UNIQ_PTR. If you want multiple smart pointers to manage the same resource, use the shared_ptr
    • Weak_ptr is shared_ptr's assistant, just to monitor whether shared_ptr managed resources are freed and not using pointers for resource management. A problem that resolves the share_ptr circular reference and returns the this pointer.


From for notes (Wiz)

C++11 Smart pointer

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.