Important: Please read the Qt Code of Conduct -

QScopedPointer and assignment value

  • Is there a way to use an assignment operator for the underlying object of a QScopedPointer, or is this verboten?


    int testFunction(bool myFlag)
    QScopedPointer<int> a(new int(0));

    if(myFlag == false)

    // I've the tried the following but can't get it to work...I'm probably misreading the
    // documentation, but this seems like it should work = 5; // does not work
    else = 10;

      return a;



  • I found the solution.

    *a = 5;

  • Good to see that you have found the solution yourself.
    Anyway here is an example of use:
    #include <QScopedPointer>
    #include <iostream>

    int foo ()
    QScopedPointer < int > iptr ( new int ( 5 ) );

    *iptr = 10;
    return *iptr;


    int main(int argc, char *argv[])
    std:: cout << foo () << std::endl;

    Scoped and shared pointer are designed to be used as simple pointers. However, to explain it simple, they avoid memory leaks and access of already released memory by automatic handling of deletion.

  • Thanks for the example.

Log in to reply