Jump to content
  • Advertisement
Sign in to follow this  
Brenton Gray

Returning a pointer to an object from a list

This topic is 2534 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

[color=#000000][font=Arial,]Long time reader first time question asker. I have a list of objects in a class FutureEvent where I want to be able to go something like futureEvents.getNextEvent(). This is currently what I have which works however because of the New call I think this is the cause of my major memory leak. Any help would be greatly appreciated. How else can I return the pointer to the next event. Thanks[/font]

[color=#000000][font=Arial,]
EVENT* FutureEvent::getNextEvent()
{
EVENT* nextEvent = new EVENT;
*nextEvent = futureEvents.front();
futureEvents.pop_front();
return nextEvent;
}
[/font]

Share this post


Link to post
Share on other sites
Advertisement
One of the following


EVENT FutureEvent::getNextEvent()
{
EVENT ret(futureEvents.front());
futureEvents.pop_front();
return ret;
}


Or

// Could also use std::unique_ptr, boost::shared_ptr, ...
std::auto_ptr<EVENT> FutureEvent::getNextEvent()
{
std::auto_ptr<EVENT> ret(new Event(futureEvents.front()));
futureEvents.pop_front();
return ret;
}


Or

void FutureEvent::getNextEvent(EVENT &ret)
{
ret = futureEvents.front();
futureEvents.pop_front();
}


Or

void FutureEvent::getNextEvent(std::list<Event> &receiver)
{
receiver.splice(receiver.end(), futureEvents.begin()); // TODO: check order of arguments, can never remember
}


The last one is the most complex, but has the nice property of not involving any copying at all (of EVENTs).
The 2nd one is closest to your original, but uses dynamic allocation unnecessarily, I'd say.

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!