Sign in to follow this  
Solid_Spy

How to access variables from weak_ptr?

Recommended Posts

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--;
        }
    }

Share this post


Link to post
Share on other sites

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.

Edited by BrentChua

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this