Jump to content
  • Advertisement
Sign in to follow this  
Solid_Spy

How to access variables from weak_ptr?

This topic is 2150 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

Edited by BrentChua

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!