I would like some help and an explanation please, I am a bit confused :(
I have a 'weak' manager which holds weak_ptr
's to other objects in my program. I would like to know when a weak_ptr
becomes expired at the point it becomes expired (i.e the shared_ptr
it points to, destructs the item).
I have looked through some interwebs about weak_ptr
binding but am I bit confused about it all so any help would be appreciated. I came across this answer (https://stackoverflow.com/questions/11680680/binding-to-a-weak-ptr), but don't really understand it, as I haven't done much with std::bind
. How does this work with weak_ptr
? If I bind a function to it, does the function get called every time something happens to the weak_ptr?
Essentially I have something like this:
#include <iostream>
#include <list>
#include <memory>
#include <functional>
#include <algorithm>
struct Obj {};
class weakManager
{
public:
unsigned int addItem(std::shared_ptr<Obj>& item)
{
items_.push_back(std::weak_ptr<Obj>(item));
return items_.size() - 1;
}
void addObserver(std::function<void(unsigned int ID)> observer)
{
obsevers_.push_back(observer);
}
unsigned int getValidItems()
{
unsigned int validItems = 0;
std::for_each(items_.begin(), items_.end(), [&validItems](std::weak_ptr<Obj>& item)
{
if (!item.expired())
++validItems;
});
return validItems;
}
private:
std::list<std::weak_ptr<Obj>> items_;
std::list<std::function<void(unsigned int ID)>> obsevers_;
};
int main(int argc, const char * argv[])
{
weakManager manager;
manager.addObserver([](unsigned int ID)
{
std::cout << "Observer says, item " << ID << " expired...\n";
});
{
std::shared_ptr<Obj> someItem(new Obj);
std::cout << "Item with ID : " << manager.addItem(someItem) << " added.\n";
std::cout << "Manager has " << manager.getValidItems() << " valid item(s).\n";
}
std::cout << "Manager has " << manager.getValidItems() << " valid item(s).\n";
return 0;
}
Currently I have to manually check which items in the manager are not expired. I would like to be able to call the 'observer' callback when the item gets destructed (i.e the weak_ptr
becomes expired, without a manual call to getValidItems
.
Any help would be appreicated. Many thanks.