You could implement a solution with shared_ptr and weak_ptr as eerorika suggested by doing something like this. You might prefer this solution to unique_ptr if you don't want the Factory to be the owner of the objects which determines when things are invalid.
Your factory class could look something like this:
class Factory {
public:
std::shared_ptr<MyObject> create();
std::vector<std::weak_ptr<MyObject>>& getObjects();
private:
std::vector<std::weak_ptr<MyObject>> objects;
void cullInvalidObjects();
};
We simply create a weak_ptr from the shared_ptr of the object in the factory method:
std::shared_ptr<MyObject> Factory::create()
{
auto object = std::make_shared<MyObject>();
std::weak_ptr<MyObject> weakObject = object;
objects.push_back(weakObject);
return object;
};
The factory can have an internal method that culls objects that are no longer valid:
void Factory::cullInvalidObjects()
{
auto iter = objects.begin();
while (iter != objects.end())
{
if ((*iter).expired())
{
objects.erase(iter++);
}
}
}
and then when getting objects to work on them, you would probably want to cull the list before providing it:
std::vector<std::weak_ptr<MyObject>>& Factory::getObjects()
{
cullInvalidObjects()
return objects;
}
Alternatively, rather than culling you could just get the list and then check for validity in your functions that process it. This is probably not the best solution if you have a large number of invalid items.
void callSomeMethod(std::vector<std::weak_ptr<MyObject>>& objects)
{
for (auto wObj : objects)
{
auto sObj = wObj.lock();
if(p)
{
p->someMethod();
}
}
}