TGUI Forum

General Category => Help requests => Topic started by: Kvaz1r on 25 August 2019, 12:05:22

Title: Closing MessageBox produce a crash.
Post by: Kvaz1r on 25 August 2019, 12:05:22
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:

Code: [Select]
#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();
}
}
Title: Re: Closing MessageBox produce a crash.
Post by: texus on 25 August 2019, 12:21:23
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.
Title: Re: Closing MessageBox produce a crash.
Post by: Kvaz1r on 25 August 2019, 13:45:34
O, now I see. Silly mistake, thank you.