c++booststlshared-ptrptr-vector

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:

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?


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.