There is a Factory class in my project, which returns std::shared_ptr<MyClass>
, if the Create
method is called. The factory is not the owner, but it maintains a list of created objects. Sometimes the factory needs to iterate over the created objects which are still used, or count them.
I implemented this using std::vector<std::weak_ptr<MyClass>>
. The iteration looks like this:
for (std::weak_ptr<MyClass> wp : weak_list) {
if (auto sp = wp.lock()) {
//..
}
}
The Create
function:
std::shared_ptr<MyClass> Create(/* ... */) {
std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
//...
weak_list.push_back(obj);
return obj;
}
Is vector the best container for a list like this? Maybe std::set
would be better.
If I implement this using a vector, I have to check regularly for expired pointers in the list and remove them
What is the preferred way to store a list of weak pointers in the factory class?