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?