Closing MessageBox produce a crash.

Started by Kvaz1r, 25 August 2019, 12:05:22

Kvaz1r

I want to create a MessageBox on menu click and close it via Cancel button. But calling close in ButtonPressed handler cause a crash. How it to do correctly?

MCVE:

#include <TGUI/TGUI.hpp>
#include <iostream>

static auto Edit = L"Edit";

int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "TGUI window");
tgui::Gui gui(window);
tgui::MenuBar::Ptr menuBar = tgui::MenuBar::create();

menuBar->addMenu(Edit);
menuBar->addMenuItem(Edit, L"Apply");
menuBar->connectMenuItem({ Edit, L"Apply" }, [&gui]
{
auto ptr = tgui::MessageBox::create("Title", "Some warning", { "OK", "Cancel" });
gui.add(ptr);
ptr->connect("ButtonPressed", [&](const std::string& button)
{
if (button == "OK")
{
std::cout << "OK\n";
}
else if (button == "Cancel")
{
ptr->close();
}
});
});

gui.add(menuBar);

menuBar->moveToFront();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();

gui.handleEvent(event); // Pass the event to the widgets
}

window.clear();
gui.draw(); // Draw all widgets
window.display();
}
}

texus

The "&" in ptr->connect("ButtonPressed", [=](const std::string& button) should be an "=".
The lambda is storing a reference to a local value which no longer exists by the time you click the cancel button.
There is no problem in copying the ptr value in the lambda as it is a pointer.

Kvaz1r

O, now I see. Silly mistake, thank you.