Passing unique_ptr for Qt methods



  • I'm making use of unique_ptr in the code, but when I try to pass this pointer to a method Qt, the complilator complains about the conversion and does not recognize the method called passing a unique_ptr.

    @
    unique_ptr<QUiLoader> loader ( new QUiLoader());
    unique_ptr<QFile> ui_file (new QFile("Forms/MainWindow.ui"));
    ui_file->open(QFile::ReadOnly);
    return loader->load(ui_file, parent);@

    output error
    _
    error: no matching function for call to ‘QUiLoader::load(std::unique_ptr<QFile>&, QWidget*&)’
    return loader->load(ui_file, parent);
    note: no known conversion for argument 1 from ‘std::unique_ptr<QFile>’ to ‘QIODevice*’_



  • For this I need to use the function get () of unique_ptr

    @
    unique_ptr<QUiLoader> loader ( new QUiLoader());
    unique_ptr<QFile> ui_file (new QFile("Forms/MainWindow.ui"));
    ui_file->open(QFile::ReadOnly);
    return loader.get()->load(ui_file.get(), parent);
    @


  • Moderators

    Just a couple of notes.
    unique_ptr has overloaded operator-> so instead of
    @
    loader.get()->load(...
    @
    you can just write
    @
    loader->load(...
    @
    Another thing is that there's no real benefit in dynamically allocating these objects and using unique_ptr here. Actually it's worse because you need to create unique_ptr instance and reference objects indirectly.
    This essentially does the same, just faster and easier to read:
    @
    QUiLoader loader;
    QFile ui_file("Forms/MainWindow.ui");
    ui_file.open(QFile::ReadOnly);
    return loader.load(&ui_file, parent);
    @


Log in to reply
 

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