Search code examples
qtpointersqscopedpointer

Create an instance of QScopedPointer later


For example here is my code

QScopedPointer<QTimer> timer2(new QTimer);

But I want to define

QScopedPointer<QTimer> timer2; 

in mainwindow.h and create an instance

timer2(new QTimer);

in the mainwindow.cpp

How?


Solution

  • Try the following:

    // mainwindow.h
    class MainWindow : public QMainWindow
    {
    private:
        QScopedPointer<QTimer> timer2;
    };
    

    If you want to create the instance in the constructor, use the following:

    // mainwindow.cpp
    MainWindow::MainWindow()
        :timer2(new QTimer)
    {
    }
    

    Alternately, if you want to create the instance in some arbitrary member function of MainWindow, use this:

    // mainwindow.cpp
    void MainWindow::someFunction()
    {
        timer2.reset(new QTimer);
    }
    

    It's also worth reviewing initialization lists in C++ and the documentation for QScopedPointer.