8.1.  Values and Objects

[ fromfile: valueobject.xml id: valueobject ]

C++ types can be divided into two categories: value types and object types.

Instances of value types are usually relatively simple, occupy contiguous memory space, and can be copied or compared quickly. Examples of value types: Anything*, int, char, QString, QDate, and QVariant.

Any class that has a public default constructor, copy constructor, and copy assignment operator is a value type.

Instances of object types, on the other hand, are typically more complex and maintain some sort of identity. Object types are rarely copied (cloned). If cloning is permitted, the operation is usually expensive and results in a new object (graph) that has a separate identity from the original.

The designers of QObject asserted an unequivocal "no-copy" policy by designating its assignment operator and copy constructor private. This effectively prevents the compiler from generating assignment operators and copy constructors for QObject-derived classes. One consequence of this scheme is that any attempt to pass or return QObject-derived classes by value to or from functions results in a compile time error.

[Tip] No Heap Value Types

There is never a good reason to create a QList, QString, QHash, QImage, or any other QVariant-related type on the heap. Don't do it. Let Qt do the reference counting and memory management for you.