Boost shared_ptr示例程序

时间:2016-02-11 01:14:58

标签: c++ boost foreach shared-ptr

我试图熟悉boost shared ptr。我遇到了以下示例。

#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>

/*  The application will produce a series of
*  objects of type Foo which later must be
*  accessed both by occurrence (std::vector)
*  and by ordering relationship (std::set).
*/

struct Foo
{
    int x;

    Foo( int y ) : x(y)
    {

    }
    ~Foo()
    {
        std::cout << "Destructing a Foo with x=" << x << "\n";
    }
};

typedef boost::shared_ptr<Foo> FooPtr;

struct FooPtrOps
{
    bool operator()( const FooPtr & a, const FooPtr & b )
    {
        return true; //a->x > b->x;
    }
    void operator()( const FooPtr & a )
    {
        std::cout << a->x << "\n";
    }
};

int main()
{
    std::vector<FooPtr>         foo_vector;
    std::set<FooPtr,FooPtrOps>  foo_set; // NOT multiset!

    FooPtr foo_ptr( new Foo( 2 ) );
    foo_vector.push_back( foo_ptr );
    foo_set.insert( foo_ptr );

    foo_ptr.reset( new Foo( 1 ) );
    foo_vector.push_back( foo_ptr );
    foo_set.insert( foo_ptr );

    foo_ptr.reset( new Foo( 3 ) );
    foo_vector.push_back( foo_ptr );
    foo_set.insert( foo_ptr );

    foo_ptr.reset ( new Foo( 2 ) );
    foo_vector.push_back( foo_ptr );
    foo_set.insert( foo_ptr );

    std::cout << "foo_vector:\n";
    std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );

    std::cout << "\nfoo_set:\n";
    std::for_each( foo_set.begin(), foo_set.end(), FooPtrOps() );
    std::cout << "\n";

    return 0;
}

我的问题是for_each()循环,它如何演示shared_ptr的功能?它们传递给for_each()循环的第三个参数是FooPtrOps()(我假设它是类FooPtrOps()中的重载operator())。但签名似乎与类中提供的定义不匹配。仍然不清楚这如何证明boost_shared_ptr

的功能

我为上述程序获得的输出是

foo_vector:
2
1
3
2

foo_set:
2
3
1
2

Destructing a Foo with x=2
Destructing a Foo with x=1
Destructing a Foo with x=3
Destructing a Foo with x=2

0 个答案:

没有答案