Nominate our 2022 Qt Champions!

Casting a auto_ptr<QWidget> to QWidget

  • Hi I am trying to cast a auto_ptr<QWidget> to a QWidget. I have tried multiple things : including

    std::auto_ptr<QWidget> nativeWidget;
    QWidget widget=static_cast<auto_ptr<QWidget> >(nativeWidget);

    It gives me an error that std::auto_ptr<QWidget> cannot be cast as a QWidget.
    How can I cast it?

  • Moderators

    Since QWidget derives from QObject, there are no assignment/copy operators available. You need to use only pointer types (unless you construct it on the stack)

  • Moderators

    anyway, there is no need to do a cast in your case:

    QWidget* widget = nativeWidget.get(); // or use release(); read the docs to see what is more applicable for your usecase

  • If you have C++11 capabilities then you are better using std::unique_ptr<T>, std::auto_ptr<T> is deprecated. That too has std::unique_ptr<T>::get() to access the raw pointer and std::unique_ptr<T>::release() to take over ownership of the object pointed to.

Log in to reply