How to delete widget if constructor fails?



  • How to prevent show widget, if it's constructor somehow failed?

    For example I use filedialog in constructor, and if cancel is clicked, I don't want to show that.


  • Lifetime Qt Champion

    Hi,

    I would say it's a bad design. If your widget should not be constructed based on a condition you should check that condition before trying to build your widget not in its constructor.


  • Moderators

    i agree with SGaist.
    But if you can't do that (for whatever reason) it's better design to implement an initialization method:
    @
    MyObject* obj = new MyObject;
    if( obj->init() )
    {
    //work with "obj"
    }
    else
    {
    //error handling
    }
    @



  • Making the constructor fail as part of the possible 'normal' application behaviour is not only very bad design as already stated earlier, it is also quite dangerous. Remember, the destructor is only called on fully constructed objects. If you have an object which has to do some cleanup inside the desctructor, e.g. free some sort of resource, then if the constructor fails for whatever reason then its destructor will never be called.



  • I meant not exactly fails with exception or something. In my case in constructor I call filedialog, and if user haven't chosen a file we should quit.



  • Hi,
    It's always a "bad" idea to have user interface in a constructor. The event loop might not even be running when you want to display the filedialog, so strange things might happen.
    Like raven-worx showed, construct your object, when it is constructed call the "init" function of the object to select/open the file dialog. When cancel is pressed do something else.
    Greetz



  • [quote author="aptyp" date="1375714650"]I meant not exactly fails with exception or something. In my case in constructor I call filedialog, and if user haven't chosen a file we should quit.[/quote]

    As others said before, the actual constructor should never fail.

    But you could use a static newInstance() function that handles everything:
    @MyWidget *MyWidget::newInstance()
    {
    MyWidget *obj = new MyWidget();
    bool success = obj->doSomethingThatMightFail();
    if(!success)
    {
    delete obj;
    obj = NULL;
    }
    return obj;
    }@

    The actual constructor of MyWidget should be made private.

    Construct a new instance like this:
    @MyWidget *widget = MyWidget::newInstance();@

    Don't forget to check whether the returned pointer is NULL ;-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.