Funny I was just working on weak pointers (developing my own version) last night!
Anyway, weak_ptr has a function called expired() which tells you if the data is still valid or not.
But if you want to get the valid data of the weak_ptr using expired() may cause some problems. Take a look at this code:
weak_ptr<SomeSystem> gpSomeSysWPtr;
void SomeFunc( void )
{
if ( gpSomeSysWPtr.expired() == false ) // This takes one cpu instruction
{
shared_ptr<SomeSystem> pSystem = gpSomeSysWPtr.Lock(); // This takes another instruction
// Between the if statement and lock() something could happend that invalidates gpSomeSysWPtr...
}
}
If that was running on a single-threaded system that'll probably be fine. But if that's being reference and edited in multiple threads, who knows what could happen between the if() and lock() ( I haven't really confirmed this but this is my hunch).
To fix the problem you can do this instead:
for(int i = 0; i < renderableObjects.size(); i++)
{
if( (std::shared_ptr<RenderableObject> r = renderableObjects[i].lock()) == false)
{
renderableObjects.erase(renderableObjects.begin() + i);
i--;
}
}
shared_ptr has a cast operator bool that returns true if the shared_ptr is valid or not.