You want to use pointers if you want all control over the lifetime of an object. for example
If you want to build a class member at some point after processing the initialization list in the constructor.
If you want to destroy a class member at some point before starting the epilogue destructor created by the compiler.
It is completely safe not to use pointers when you are fine with creating a compiler and destroying object instances for you.
Raw pointers are prone to errors whenever they own the resource they point to: it is an error to forget to delete the resource that belongs to it, delete the resource several times, or dereference an already deleted resource.
The use of raw pointers (as opposed to smart pointers) that do not own the resource — when the resource is freed by someone else — can still cause premature optimization. Using source pointers is prone to turning “small” code changes into resource leaks:
class X : public QObject { QObject * a; public:
Smart pointers - C ++ 11 std::unique_ptr , Qt 4.6 QScopedPointer - ensure that deletion always occurs, and that access to the remote resource is equivalent to dereferencing the null pointer and, thus, is nominally caught and signaled by the processor equipment.
In C ++, the order of constructing and destroying class members and automatic variables is fixed. In the examples below, the construction order is always a , then b , and the destruction order is always b , then a . This is very important .
class C { A a; B b; }; void test() { A a; B b; }
Thus, the following code is valid and behaves correctly, at least in Qt 3, Qt 4 and Qt 5, unless otherwise specified.
class C : public QWidget { QWidget a; QLabel b; public: C(QWidget * parent = 0) : QWidget(parent), a(this), b(&a) {} }
In all cases, the order of construction: c, a, b ; destruction order: b, a, c .