Search code examples
c++memoryvectormemory-leaksscoping

Dealing with memory, when using std::vector


I'm using vector with my own class type:

std::vector<CItem> m_vItems;

In my class I'm initializing SFML types like texture and sprite:

class CItem
{
    (...)
    sf::Texture m_Texture;
    sf::Sprite m_Sprite;
    sf::IntRect* m_pRect;
    (...)
}

I'm trying to pass object to my vector declared as member of other class CLevel and I'm doing it inside method of that class like this:

CItem *temp = new CItem(x, y, kind);
m_vItems.push_back(*temp);

As you see, I'm not deleteing temp pointer with delete, but in destructor of class CLevel I've got a simple line:

std::vector<CItem>().swap(m_vItems);

And I'm little confused about memory leaks. Is my program has got some of these or the line above solving problem and my example has been correctly written?


Solution

  • CItem *temp = new CItem(x, y, kind);
    m_vItems.push_back(*temp); // here a copy of *temp is pushed into vector
    

    You should call delete somewhere to delete what you allocated with temp:

    delete temp;
    

    to avoid memory leak. Any call to new must have matching call to delete somewhere. This doesn't influence a copy of temp that was pushed into vector. It still exist as long as vector exists.

    The best is to use just:

    m_vItems.push_back(CItem(x, y, kind)); // implement this constructor correctly
                                           // to avoid uninitialized variables
    

    Always when leaks are concern you can profile your program with tool: Valgrind or Visual Leak Detector.