开发者

C++ Sharing elements in a boost::ptr_container?

Please consider the following piece of code:

int main()
{
    typedef boost::ptr_vector<int> ptr_vector;

    ptr_vector vec0;
    vec0.push_back(new int(1));
    vec0.push_back(new int(2));
    vec0.push_back(new int(3));
    vec0.push_back(new int(4));
    vec0.push_back(new int(5));

    ptr_vector::iterator last  = boost::prior(vec0.end()),
                         first = boost::prior(last, 3);

    ptr_vector vec1(first, last); // this will copy '2, 3, 4' to vec1

    struct print
    {
        void operator()(int const& i) {
            std::cout << i.m_i << std::endl;
        }
    };

    std::for_each(vec0.begin(), vec0.end(开发者_开发问答), print());   // 1, 2, 3, 4, 5
    std::for_each(vec1.begin(), vec1.end(), print());   // 2, 3, 4

    return 0;
}

I don't want to copy the elements into vec1, but sharing in a way that shared_ptr<> provides. My requirements basically are:

  • Sharing the same instances of a range of objects, which are part of a container, in another container instance
  • Don't want to share one instance in more than these two containers
  • Want to be notified when one element is "suddenly" erased from the other container (or at least get check this, e.g. something like shared_ptr::unique())

Both containers are part of the same class. So, they have the same scope and will be destroyed at the same time. The constructor of these class constructs both containers. After construction there won't be any modification to these containers.

Do I need to use a std::vector<> of shared_ptr<> instead or is there any other solution?


Yes, you should use a vector<shared_ptr<int>>.

Since you're only working with ranges, you could put together a custom solution that keeps track of the ranges and their intersections (for implementing unique.) Then, you could store everything in vector and have the ranges index into that. This would probably be faster (just on account of the avoided cache misses), but it would be more work to implement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜