Boost Smart pointer-basic knowledge

Source: Internet
Author: User

Simple Introduction

Memory management has always been a relatively cumbersome problem in C + +, but smart pointers can be a very good solution to the problem, at the time of initialization has been scheduled to delete. To resolve the worries. The first edition of the C + + standard, revised in 1998, provided only a smart pointer: Std::auto_ptr (now obsolete), which is basically like a normal pointer: access to a dynamically allocated object through the address.

Std::auto_ptr is considered a smart pointer. is because it invokes the delete operator at the time of the destructor to voluntarily release the included object.

This, of course, requires the address of an object returned by the new operator to be passed to it at initialization time. Since the destructor of Std::auto_ptr calls the delete operator. The memory of the object it contains is guaranteed to be released.

This is one of the strengths of smart pointers.
This is even more important when trying to relate to an exception: there is no std::auto_ptr this smart pointer. Each function that dynamically allocates memory needs to catch all possible exceptions. To ensure that the memory is freed before the exception is passed to the caller of the function. The smart pointer series of the Boost C + + library provides a number of smart pointers that can be used in a variety of situations.


RAII

RAII full name is "Resource acquisition is initialization", literal translation is "resource acquisition is initialization".

But this translation does not show the true meaning of this habitual use method. The advantage of RAII is that it provides a way for resources to manage themselves proactively. RAII can release resources correctly when there are anomalies, rollbacks, and so on.


Raii is also the basic principle of smart pointers, and smart pointers are just one example of this idiom. The smart pointer ensures that under no circumstances. Dynamically allocated memory can be released correctly. This frees the developer from the task. This includes programs that are interrupted because of an exception. A scenario in which the code that was originally used to free memory was skipped. This is ensured by initializing the smart pointer with the address of a dynamically allocated object and freeing the memory at the time of the destructor.

Because the destructor is always running. This includes the memory that will always be released.
Many C + + applications require dynamic management of memory, so smart pointers are a very important type of RAII. Just RAII itself is suitable for many other scenarios.


scoped_ptr

Boost::scoped_ptr is a simple smart pointer that guarantees that the object will be released on its own initiative after leaving the scope.
The implementation of BOOST::SCOPED_PTR is the use of objects on a stack to manage objects on a heap. This allows the objects on the heap to be deleted on their own initiative as the objects on the stack are destroyed.


Boost::scoped_ptr Features

    • Cannot convert all rights
      The object life cycle managed by SCOPED_PTR is limited to only one interval (the "{}" where the pointer resides). Cannot be passed outside the range, which means that the Scoped_ptr object cannot be returned as a function's return value.

    • Cannot share all rights
      This feature makes the pointer easy to use on the one hand.

      There is also a weakness in functionality: it cannot be used in STL containers.

    • cannot be used to manage array objects
      Because Scoped_ptr deletes the managed objects by using Delete. The array object must be deleted by deletep[]. Therefore, SCOPED_PTR cannot manage array objects, assuming that the Boost::scoped_array class is required to manage array objects.

shared_ptr

Boost::scoped_ptr is easy to use, though. But it can not share the full weight of the characteristics, but greatly restricting its use. SHARED_PTR can solve this limitation.

in standard C + + for std::shared_ptr, in the boost C + + library. This smart pointer is named BOOST::SHARED_PTR.
The shared_ptr management mechanism is actually not complex, that is, the object to be managed reference count, when a new shared_ptr to manage the object, the reference count of the object is added one; when you lower a shared_ptr to manage the object, The reference count of the object is reduced by one. Assuming that the object has a reference count of 0, the call to delete frees the memory it occupies, no matter what pointers are administered to it.

Boost::shared_ptr Features

    • The ability to share all the rights of an object
      Shared_ptr is able to share all the rights of an object compared to scoped_ptr. So the copy stored in the container (which contains the additional copies created by the container when needed) is the same as the original. The ability to safely use dynamically allocated objects in standard containers.

    • Thread-Safe
      The Shared_ptr object provides the same level of thread security as the built-in type. An shared_ptr instance can be "read" by multiple threads at the same time (using only the invariant operation). Different shared_ptr instances can be "written" by multiple threads at the same time (using variable operations like operator= or reset) (even if these instances are copies and share the reference count below). No matter what else the result of the interview at the same time will result in undefined behavior. ”
      • It is safe for the same shared_ptr to be "read" by multiple threads.
      • It is not safe for the same shared_ptr to be "written" by multiple threads.

      • Different shared_ptr that share reference counts are "written" by multiple threads to be secure.
    • Support your own definition of deleter

Boost::shared_ptr precautions

    • SHARED_PTR can be used as a function's reference or as a return value of a function, which is equivalent to using a copy construct
    • SHARED_PTR can be used in standard containers, which is equivalent to using a copy construct
    • Be careful not to loop the reference, which will cause the object to not be released

weak_ptr

shared_ptr reference counting is a convenient memory management mechanism, but it has a very big drawback, which is that you cannot manage the objects of a circular reference. Like what:

#include <string> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/weak_ Ptr.hpp>class parent;class children;typedef boost::shared_ptr<parent> parent_ptr;typedef boost::shared_ptr <children> children_ptr;class parent{public:    ~parent () {std::cout << "destroying parent\n";} Public:    children_ptr Children;}; Class Children{public:    ~children () {std::cout << "destroying children\n";} Public:    parent_ptr parent;}; void Test () {    parent_ptr father (new parent ());    Children_ptr Son (new children);    Father->children = Son;    Son->parent = Father;} void Main () {    std::cout<< "begin test...\n";    Test ();    std::cout<< "End test.\n";}

Execution of the program can be seen, even after exiting the test function, because the parent and children objects reference each other , their reference count is 1. You cannot voluntarily release it, and at this point the two objects are no longer able to access the question, which causes a memory leak.


Generally speaking, there are three possible ways to remove such a circular reference:

    • When only the last reference is left, you need to manually break the circular reference release object.

    • When the lifetime of the parent exceeds the lifetime of children. Children instead, use a normal pointer to point to the parent.
    • A smart pointer using a weak reference breaks such a circular reference.

      A strong reference is used on the parent child reference, and a weak reference is used when the child is referring to the parent, thus avoiding circular references.

Although all of these three methods are feasible. But both Method 1 and Method 2 need the program Ape manual control, trouble and easy error.

Here is a look at the third method and the weak reference in Boost smart pointer boost::weak_ptr.

Strong references
A strong reference when the referenced object is alive. This reference also exists (that is, when there is at least one strong reference, then the object cannot be freed).

Boost::share_ptr is a strong reference.

Weak references
It is only a reference when the object exists. A weak reference can be detected when the object is not present, thus avoiding illegal access, and the weak reference does not alter the object's reference count. This means that weak references to it are not properly managed by the object's memory, functionally similar to normal pointers, however a larger difference is. A weak reference can detect whether the object being managed has been disposed of. Thus avoiding access to illegal memory.

In C + +, a normal pointer can be considered a weak reference, and a smart pointer can be considered a strong reference. Although pointers cannot be counted as "real" weak references, weak references should be able to know when an object becomes inaccessible.

Breaking circular references
A strong reference is used on the parent child reference, and a weak reference is used when the child is referring to the parent, thus avoiding circular references.

For a specific example see boost smart pointer-weak_ptrclass children{public:    ~children () {std::cout << "destroying children\n";} Public:    boost::weak_ptr<parent> parent;};

Although the circular reference can be effectively lifted by a weak reference pointer, it must be used in cases where the program ape can foresee a circular reference. It can also be said that this is a compile-time solution, assuming that the program has a circular reference during execution. will still cause a memory leak.


intrusive_ptr

In most cases, we do not use boost::intrusive_ptr, because the ability to share all rights has been provided in Boost::shared_ptr. and non-pluggable smart pointers are more flexible than plug-in smart pointers.


But. Sometimes it also requires a plug-in reference count, either because of old code or for integration with third-party classes. When there is such a need. The ability to use INTRUSIVE_PTR, which has the same semantics as other boost smart pointers. Let's say you've used other boost smart pointers. You'll find that all smart pointers have a consistent interface, whether they're plugged in or not.


Classes that use intrusive_ptr must be able to provide a reference count. Intrusive_ptr by calling two functions. Intrusive_ptr_add_ref and Intrusive_ptr_release to manage reference counts. These two functions must correctly manipulate the insertion reference count to ensure that the intrusive_ptr works correctly.

In cases where a reference count has been built into a class using intrusive_ptr, the implementation of support for INTRUSIVE_PTR is the implementation of both functions.

In some cases, it is possible to create a parameter version number for both functions, and then use the same implementation for all types with a plug-in reference count.

Most of the time, the best place to declare these two functions is the namespace in which the type they support is located. Use intrusive_ptr in the following situations

    • You need to use this as a smart pointer.
    • Existing code uses or provides a plug-in reference count.
    • The size of the smart pointer must be equal to the size of the bare pointer.

Control Boost::shared_ptr

Using the Boost::shared_ptr user class This province does not need to have a reference count function. Instead, it is provided by Boost::shared_ptr. One of the pitfalls of using boost::shared_ptr is to create boost::shared_ptr multiple times with a raw pointer. This will cause the raw pointer to be destroyed multiple times when Boost::shared_ptr is destructed. This cannot be used for example:

int *a = new int(5);boost::shared_ptr ptr1(a);boost::shared_ptr ptr2(a);  //错误!

The boost::intrusive_ptr is fully boost::shared_ptr and does not have the shared_ptr problem of being able to create multiple intrusive _ptr with raw pointer because the reference count ref The _count object, shared_ptr, is placed in the shared_ptr structure, and the target object T appears with two reference counters for the same object by inheriting the Intrusive_ptr_base reference count as the internal member variable of the T object.

So why do you usually inspire people to use shared_ptr instead of intrusive_ptr, shared_ptr is not intrusive. Ability to point to arbitrary types of objects, while intrusive_ptr the object to which it is pointing. You need to inherit intrusive_ptr_base, and even if not, the reference count member is created.


References link
Http://zh.wikipedia.org/wiki/%E5%BC%B1%E5%BC%95%E7%94%A8 http://www.codeproject.com/Articles/8394/ Smart-pointers-to-boost-your-code http://www.cnblogs.com/TianFang/archive/2008/09/15/1291050.html/HTTP Www.cnblogs.com/TianFang/archive/2008/09/19/1294521.html http://www.cnblogs.com/TianFang/archive/2008/09/20/ 1294590.html http://blog.csdn.net/alai04/article/details/572959 http://blog.csdn.net/yockie/article/details/ 8840205 http://blog.csdn.net/juana1/article/details/6624222 http://blog.csdn.net/ithzhang/article/details/ 9038929 http://blog.csdn.net/hunter8777/article/details/6327704 http://blog.csdn.net/yusiguyuan/article/details/ 22037833


from:http://blog.csdn.net/liufei_learning/article/details/34808549

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

Boost Smart pointer-basic knowledge

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.