could somebody please explain why this happens? I have written the following:
1) a WindowManager class which is implemented as a singleton and has an Instance() method, defined like so:
static WindowManager * instance_;
//...
WindowManager * WindowManager::instance_ = 0;
WindowManager & WindowManager::Instance()
{
if (!instance_)
instance_ = new WindowManager();
return *instance_;
}
2) a WindowManager::createWindow method that returns a reference to a newly created window, defined like so:
Window & WindowManager::createWindow()
{
windows_.push_back(Window());
return windows_.at(windows_.size() - 1);
}
3) a Window::print method that prints a message inside the window
In my main program, I have written the following:
ui::Window & win1 = ui::WindowManager::Instance().createWindow();
ui::Window & win2 = ui::WindowManager::Instance().createWindow();
win1.print("First window");
win2.print("Second window");
This does not work! Only the second call to print is executed (for win2).
However, if I change the order, like so:
ui::Window & win1 = ui::WindowManager::Instance().createWindow();
win1.print("First window");
ui::Window & win2 = ui::WindowManager::Instance().createWindow();
win2.print("Second window");
then everything works as expected. If anybody could shed some light on this situation, any help would be greatly appreciated.
Here you have quick example which illustrates the problem:
Compile and run as it is and see what is printed to stdout.
Then uncomment
reserve()call, compile and run once again and compare with previous output.The problem is that
std::vector::push_backcauses reallocation of the data internally. This invalidates all references, pointers or iterators to vector elements you’ve obtained before the reallocation.