C++ : a nasty bug
It took me 2 days to figure out this bug in C++.
The context
I use ncurses and I want to manage several windows. I created a class (Window) with all the methods I need.
class Window {
private:
WINDOW *win;
...
public:
...
}
No issue here.
To store my objects, I used a vector of pointers:
std::vector<Window*> Windows;
The bug
I want to create 2 windows, so I did the following:
Window *A = new Window(...); // Instantiate the class Window, implicitely calling the constructor Windows.push_back(*A); // Adding object A to the vectors Window *B = new Window(...); // New instantiation Windows.push_back(*B); // Adding object B to the vectorsThe bug was here: when I pushed back the second object (B), the memory manager decided to reallocate the vectors, because vectors must be contiguous. Doing so implicitely called the destructor of the first object; the window A disappeared.
Possible solutions
- Reserve memory for the vectors
Windows.reserve(10); // Reserves 10 Windows
Good, but limits the number of windows. - Use a
std::listinstead ofstd::vectorBetter, no limits on the number of windows.


Comments