How to access variables from weak_ptr?

Started by
0 comments, last by MrCodeSushi 10 years, 7 months ago

Hey, I've created a list of weak_ptr's for game objects, and i want to access their fields, but they say that they are innaccessible. Why is this?


for(int i = 0; i < renderableObjects.size(); i++)
    {
        std::shared_ptr<RenderableObject> r = renderableObjects[i].lock();
                
        if(r->getDead == true)
        {
            renderableObjects.erase(renderableObjects.begin() + i);
            i--;
        }
    }

View my game dev blog here!

Advertisement

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.

This topic is closed to new replies.

Advertisement