Brenton Gray
Brenton Gray

Reputation: 21

Returning a pointer to an object from a list

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

EVENT* FutureEvent::getNextEvent()
{
EVENT* nextEvent = new EVENT;
*nextEvent = futureEvents.front();
futureEvents.pop_front();
return nextEvent;
}

Upvotes: 2

Views: 935

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234624

If you don't delete the result of this function anywhere, this is certainly the cause of a memory leak.

Possible solutions include:

  1. Returning by value

    With this approach you don't even need to use dynamic allocation (i.e. new). You only use automatic objects, so you don't need to clean up: the memory they use is automatically released and any destructors are called automatically.

    EVENT FutureEvent::getNextEvent() {
        EVENT nextEvent = futureEvents.front();
        futureEvents.pop_front();
        return nextEvent;
    }
    
  2. Using a smart pointer

    This approach still uses dynamic allocation, but it delegates to a class that can take care of the cleanup automatically.

    std::unique_ptr<EVENT> FutureEvent::getNextEvent() {
        std::unique_ptr<EVENT> nextEvent(new EVENT(futureEvents.front()));
        futureEvents.pop_front();
        return nextEvent;
    }
    

    If your compiler doesn't support std::unique_ptr you can use one of the smart pointers in Boost, like boost::shared_ptr.

Upvotes: 4

Related Questions