Important: Please read the Qt Code of Conduct -

QPointer vs std::unique_ptr

  • Hello guys,

    I recently switched from Java to C++, as you may guess I had lot of problem with pointers at first.
    I learned to use std::unique_ptr and std::shared_ptr for different use now and now i'm doing fine.

    I just learned that there is a class QPointer that is similar to that.
    But your object must inherit Q_Object in order to use it.

    My question : Is it worth it to use QPointer or does std::unique_ptr does that job fine and/or better?
    I'm no C++ guru so I don't know about speed/efficiency but the QPointer syntax looks more simple to me.

    Thanks in advance!

  • QPointer and std::unique_ptr are not equivalent.

    QPointer just lets you know the object it is pointing is destroyed.

    std::unique_ptr deletes the object for you on destruction.

    What you are looking for is QScopedPointer.

  • Lifetime Qt Champion


    If std::unique_ptr does the job then go on, nothings wrong using it. There's no need to create a QObject derived class only to use QPointer if you already have something working.

Log in to reply