Shared pointers
This smart pointer is named BOOST::SHARED_PTR, defined in BOOST/SHARED_PTR.HPP. The smart pointer boost::shared_ptr is basically similar to boost::scoped_ptr. The key difference is that BOOST::SHARED_PTR does not necessarily have to monopolize an object. It can share ownership with other boost::shared_ptr types of smart pointers. In this case, the object is freed when the last smart pointer to the referenced object is destroyed.
Because ownership can be shared between boost::shared_ptr, any shared pointer can be duplicated, which is different from boost::scoped_ptr. This allows smart pointers to be stored in standard containers-you can't store std::auto_ptr in a standard container because they pass ownership when copied.
1#include <iostream>2#include <algorithm>3#include <vector>4#include <boost/shared_ptr.hpp>5 6 voidShow (boost::shared_ptr<int>p)7 {8Std::cout << *p <<Std::endl;9 }Ten One voidMain () A { -std::vector<boost::shared_ptr<int>>v; - theboost::shared_ptr<int>P1 (New int( One)); -boost::shared_ptr<int>P2 (New int( A)); -boost::shared_ptr<int>P3 (New int( -)); - + V.push_back (p1); - v.push_back (p2); + V.push_back (p3); A at For_each (V.begin (), V.end (), show); -}
Initializes a new object using the Boost::shared_ptr type, which is a shallow copy
1#include <iostream>2#include <boost/shared_ptr.hpp>3 4 classRunclass5 {6 Public:7 inti =0;8 Public:9Runclass (intnum): I (NUM)Ten { OneStd::cout <<"I creator"<< I <<Std::endl; A } -~Runclass () - { theStd::cout <<"I delete"<< I <<Std::endl; - } - voidprint () - { +Std::cout <<"i="<< I <<Std::endl; - } + }; A at voidShow (boost::shared_ptr<int>p) - { -Std::cout << *p <<Std::endl; - } - - voidMain () in { -BOOST::SHARED_PTR<RUNCLASS>P1 (NewRunclass (Ten));//There are call constructors to +BOOST::SHARED_PTR<RUNCLASS>P2 (p1);//shallow copy, no constructor called -Boost::shared_ptr<runclass>p3 (p1);//shallow copy, no constructor called the *P1.reset (NewRunclass ( A));//There are call constructors $ Panax NotoginsengP1->print (); -P2->print (); theP3->print (); +}
#include <boost/shared_ptr.hpp>