Create an instance of QScopedPointer later

5.2k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

What you're doing amounts to a premature pessimization. You're creating members of a MainWindow class separately and individually on the heap, when you should be simply putting them into the class as members:

// interface
#include <QMainWindow>
#include <QTimer>

class MainWindow : public QMainWindow {
  Q_OBJECT
  QTimer m_timer;
public:
  MainWindow(QWidget * parent = 0, Qt::WindowFlags flags = 0);
};

// implementation
MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
  QMainWindow(parent, flags),
  m_timer()
{
  ...
}

Of course, you would ordinarily not want to expose all the details of the MainWindow's implementation in the interface (header) file. Thus you would leverage the PIMPL idiom:

// interface
#include <QMainWindow>

class MainWindowPrivate;
class MainWindow : public QMainWindow {
  Q_OBJECT
  Q_DECLARE_PRIVATE(MainWindow)
  QScopedPointer<MainWindowPrivate> const d_ptr;
public:
  MainWindow(QWidget * parent = 0, Qt::WindowFlags flags = 0);
}

// implementation
#include "MainWindow.h"
#include <QTimer>

class MainWindowPrivate {
public:
  QTimer timer;
}

MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
  QMainWindow(parent, flags),
  d_ptr(new(MainWindowPrivate())
{
  Q_D(MainWindow);
  d->timer.start( ... );
  ...
}
0
On

Use method reset of QScopedPointer

timer2.reset(new QTimer());