The problem:
Replace naked pointers with smart QPointers
and use them with forward declared classes.
Background:
As advised by virtually all texts on modern C++, one should refrain from using naked pointers and use smart pointers instead. In the Qt toolkit there is a set of smart pointers available, with one of particular interest to me in this case: QWeakPointer
(Qt 4) or QPointer
(Qt 5), which is supposedly freely interchangeable with a naked pointer and is set to NULL
when the respective object (derived from QObject
) is deleted, thus helping prevent the all too common dangling pointer problem. Yet the requirement that the object pointed to by the QPointer
be of a QObject
-derived type prevents usage of forward declared classes.
The question: How do I combine QPointer
-type variables with forward declared classes in the class header with forward declared types?
or
How do I avoid including the whole header file for an object for which I want to use the QPointer
?
Example:
#pragma once
#include <QObject>
#include <QPointer>
class MyQWidget; // Forward-declared class
class SomeClass {
QPointer<MyQWidget> m_myWidget;
};
Note: I've read through wuestion like this one: In C++, is it possible to forward declare a class as inheriting from another class?. In my question, I'm looking for Qt-specific ways to overcome this limitation (or better design feature), if there are any.
Edit: My main compiler is MSVC 2010 and the error I get is
error C2079: 'MainWindow::m_test' uses undefined class 'QPointer<T>'
with
[
T=MyQWidget
]