I would like to create a list or map of references in C++ which automatically deletes its elements upon their destruction. Here is a structure demonstrating the idea.
class Foo;
class Bar
{
Foo foo;
};
void main(void)
{
std::vector<Foo> foos;
{
Bar bar;
foos.push_back(bar.foo);
// foos[0] should be the same reference as bar.foo
}
// bar is now destructed
// foos.size() should be 0
}
There are two things wrong with my code. When push_back() is called with a std::vector, it creates a copy of the Foo object. This would be unacceptable since the elements of foos should reflect any changes done upon bar.foo. Secondly, even if the foos vector could store references, the Foo object would not be removed from the list after leaving the scope where bar was created. Ideally, I would like the Foo reference to be removed from foos upon its destruction.
Before I implement my own solution, I’d love to know of any third party libraries (Boost, possibly?) which offer this, or any proper techniques or strategies I should be using for this. Thanks!
I think the best option is to use a container of weak pointers. (Available in Boost if your compiler doesn’t support C++11 or TR1 for some reason.)
A weak pointer will automatically invalidate itself when the target is destructed, assuming you initialized things properly.
Here’s some sample code for getting all valid pointers in a container of weak pointers.
And here’s how to clean out all invalid pointers.