Smart pointer shared_ptr

Source: Internet
Author: User

The second type of smart pointer of the boost library is shared_ptr.

Shared_ptr has the following features:

1. it can point to the same content and determine whether the content is released by reference count. The space requested by the new int is released only when all the three pointers pointing to it are released. Otherwise, the reference count is reduced by one.

#include <cassert>#include <boost/shared_ptr.hpp>int _tmain(int argc, _TCHAR* argv[]){boost::shared_ptr<int> tmp(new int(50));boost::shared_ptr<int> a = tmp;boost::shared_ptr<int> b = tmp;*a = 100;assert(*b == 100);getchar();return 0;}

2. It can be used as a container element.

#include <iostream>#include <vector>#include <boost/shared_ptr.hpp>class counter{public:static int _no;counter(){_no++;}~counter(){_no--;}static void Speak(){std::cout << "Total " << _no << " Objects!" << std::endl;}};int counter::_no = 0;int _tmain(int argc, _TCHAR* argv[]){typedef boost::shared_ptr<counter> element;typedef std::vector<element> container;typedef std::vector<element>::iterator iterator;element a(new counter());element b(new counter());element c(new counter());element d(new counter());element e(new counter());container cr;cr.push_back(a);cr.push_back(b);cr.push_back(c);cr.push_back(d);cr.push_back(e);for (iterator it = cr.begin(); it != cr.end(); ++it){(*it)->Speak();}cr.clear();getchar();return 0;}

3. shared_ptr can customize the deleteer to process non-delete and delete [] resources that can be processed, such as file descriptors in the example. The following two examples are used to copy the statement.

When shared_ptr points to a pointer, the original method of calling the pointer is: & * sp, * SP indicates the object, and * SP indicates the pointer. You can use sp. Get () instead.

# Include "Boost/shared_ptr.hpp" # include <vector> # include <cassert> # include <iostream> # include <cstdio> class filecloser {public: void operator () (File * file) {STD: cout <"The filecloser has been called with a file *, which will now be closed. \ n "; if (file! = 0) {STD: fclose (File) ;}}; int _ tmain (INT argc, _ tchar * argv []) {// file * f = STD: fopen ("test.txt", "R"); If (F = 0) {STD :: cout <"unable to open file \ n"; throw "unable to open file";} boost: shared_ptr <File> SF (F, filecloser (); STD :: fseek (SF. get (), 100, seek_set); STD: fseek (& * SF, 100, seek_set);} STD: cout <STD: Endl ;}

The second example demonstrates the safe Delete method, and demonstrates the rule for deleting a function: Implementing the operator () (type * P) {} function.

# Include "Boost/shared_ptr.hpp" # include <iostream> Class A {// nested class deleter {public: // overload operator () void operator () (A * P) {Delete P ;}}; // declare it as a friend Meta class and implement nesting to implement secure access. Friend class deleter; public: Virtual void sing () {STD: cout <"lalalalalalalalalalalalalala" ;}// constructor static boost: shared_ptr <A> createa () {boost: shared_ptr <A> P (new A (), A: deleter (); Return P;} protected: Virtual ~ A () {};}; int main () {// constructor creates a class and then calls it directly without managing any release operations. Boost: shared_ptr <A> P = A: createa ();}

To sum up, the usage of shared_ptr is as follows:

1. If there is no ownership to an object, the pointer is referenced multiple times. Which pointer releases resources will cause other pointers to become wild pointers, so shared_ptr is used to avoid this problem, shared_ptr uses the reference count method to release resources only when the last pointer is released. In other cases, the reference count is reduced by one.

2. It is applicable to the container class because it has the feature of 1. This is the main difference between it and scoped_ptr.

3. It can customize the delete function based on the referenced content. In some cases, delete and delete [] are not the method of canceling the resource. You need to use shared_ptr to customize the delete function, for Deletion rules and methods, see the sample code.

4 shared_ptr is very suitable for scenarios where the object has no ownership, so it is especially suitable for design patterns such as factory classes and constructors, and is implemented by nature. Code 2 creates a constructor function to create each object (you can modify it yourself ).

5. When the object is to be transferred to the database or to obtain the object from the database without explicit ownership (this sentence is the original document, and I did not understand the specific application, just copy it)

6. When you manage resources that require special clearing methods (this sentence is the original statement in the document, as shown in figure 3)

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.