Search code examples
c++classwxwidgets

Why does my string content disappear in class method?


I have a class:

class aeMessage : public aeDialog
{
    const wxString* message;

public:
    aeMessage(const wxString& title, const wxString& message, const char* buttons[], const int button_count, const wxSize& size);
    void configurePanel(wxPanel* panel); // Overrides method in aeDialog
};

aeMessage::aeMessage(const wxString& title, const wxString& message, const char* buttons[], const int button_count, const wxSize& size)
    : aeDialog(title, buttons, button_count, size)
{
    this->message = &message;
    std::cout << "1 Message Address = " << this->message << "\n";
    std::cout << "2 Message Text = " << *this->message << "\n";
}

On construction the output is:

1 Message Address = 0x7ff7b9a9b920
2 Message Text = This is the About dialog

I have method in the class as follows:

void aeMessage::configurePanel(wxPanel *customPanel)
{
    // Create message box

    std::cout << "3 Message Address = " << this->message << "\n";
    std::cout << "4 Message Text = " << *this->message << "\n";
}

The output is:

3 Message Address = 0x7ff7b9a9b920
4 Message Text =

Can anyone help me understand why the content of the string has disappeared? There is nothing that changes the the content of this->message. thanks

The class is being created using:

void MyApp::OnAbout(wxCommandEvent &event)
{
    // Show the About dialog box

    const int numberOfButtons{1};
    const char *buttons[numberOfButtons] = {"Ok"};
    aeMessage *custom = new aeMessage(wxT("Aetharcana"), "This is the About dialog", buttons, numberOfButtons, wxSize(600, 300));
    custom->show();
    std::cout << "Returned " << custom->getSelected() << "\n";
    custom->Destroy();
}

Solution

  • I see 2 issues happening:

    • You are passing a string literal to themessage parameter of your constructor, so the compiler has to create a temporary wxString object, which your constructor is then storing a pointer to. That temporary is destroyed as soon as your constructor exits, thus leaving the this->message pointer dangling.

    • the value of this->message is not consistent, which implies that your aeMessage::configurePanel() method is not being called on the same aeMessage object that you constructed. However, the sample code you have shown does not demonstrate this usage.