0

I have an object with some data in it:

class MyObject
{
    public:
        Recipe(<Some Arguments>);
}

and a dialog to edit the values of this object. This dialog gets a reference to this object and visualizes the values. I use a reference because I want to hold the data only once in memory. So I pass a reference to my data to every window which uses the data.

class MyDialog: public QDialog
{
    private:
        Ui::MyDialog* _mUi;

        MyObject _mNew;
        MyObject& _mOld;
};

MyDialog::MyDialog(MyObject& Old, QWidget* parent) : QDialog(parent),
                                                     _mUi(new Ui::MyDialog),
                                                     _mNew(Old)
                                                     _mOld(Old)
{
    _mUi->setupUi(this);

    // Visualize the values from "Old" in the GUI
}

The dialog also has some slots to fill the Object _mNew with newer input data from the GUI. When the user has finished the editing he can leave the window by clicking Save, which triggers the following code:

if(button == _mUi->buttonBox->button(QDialogButtonBox::Save))
{
    // Overwrite the old values
    _mOld = _mNew;
}

The values get updated and everything works fine.

But I´m not sure that this is a good solution. Is it a good practice to pass a reference to a data pool (MyObject) into a dialog, edit the values and overwrite the reference with a new address or is there a better approach to realize some kind of editing method?

Kampi
  • 1,798
  • 18
  • 26
  • What is your guarantee that the reference does not become a dangling reference? – JaMiT Feb 08 '20 at 14:45
  • @JaMiT what do you mean? – Kampi Feb 08 '20 at 14:56
  • Suppose you set a variable using something like `test = new MyDialog(Old, parent)`. If the lifetime of `*test` exceeds the lifetime of `Old`, then `test->_mOld` becomes a reference to data that no longer exists (a.k.a. a dangling reference). If you have no way to guarantee that this will not happen, then your code is broken. – JaMiT Feb 08 '20 at 16:17
  • @JaMiT the source for the reference is a fixed variable (a list) is held in my main window. So as long the program lives (and in this case my main window) the source for the references doesn´t get destroyed. – Kampi Feb 08 '20 at 16:34
  • So you are relying on remembering to never change that assumption? Tends to be a bit fragile. You might want to look at [Alternatives for dangling pointers and references](https://stackoverflow.com/questions/4270902/dangling-reference-alternatives-for-dangling-pointers-and-references) and [What is a smart pointer and when should I use one?](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one/106614#106614) The former might even be a duplicate of this, even though the perspective is a little different. (Personally, I'd look into `shared_ptr`.) – JaMiT Feb 08 '20 at 17:21

0 Answers0