Log in / Register
Home arrow Computer Science arrow Learn BlackBerry 10 App Development
< Prev   CONTENTS   Next >

QObject Identity

QObjects feel strongly about their identity. In other words, you cannot use them as value objects. Having value semantics means for an object that only its value counts and that any copy of the object is equivalent. However, as mentioned previously, when considering pass-by-value semantics, QObjects cannot be copied or assigned. Before explaining how this is enforced, let me quickly recap two fundamental concepts that I brushed over when I mentioned pass-by-value semantics. In C++, you can define a copy constructor and an assignment operator. The copy constructor is used, for example, to pass the object by value to a function (or return an object by value from an function).

The assignment operator (=) is used to assign one object to another (for example obj1 = obj2). I am not going to show you how to implement these operators but instead simply mention their signature:

n Copy constructor: The typical form of the copy constructor is MyClass::MyClass(const MyClass& original) and is used for creating a new copy of an existing instance. Typically, the copy constructor is called when passing an object by value to a function. Note that the copy constructor takes a constant reference to the original object in order to create the copy. If you do

not provide a copy constructor, the compiler will implicitly create one for you doing a member-wise copy of the original object. Also note that you must pass a reference to the original object. The member-wise copy is problematic if your class contains pointers to dynamically allocated resources. In this case, the compiler-generated version of the constructor simply performs a “shallow” copy of the original object—resulting in all sorts of memory ownership problems.

n Assignment operator: The typical assignment operator is const MyClass& MyClass::operator=(const MyClass& rhs). The assignment operator is called when you assign one object to another. Here again, if you do not provide one, the compiler will implicitly create an assignment operator for you, which does a member-wise copy of the original object.

Because a QObject is not intended to be assigned or copied, it disables the use of the copy constructor and assignment operator using the Q_DISABLE_COPY(ClassName) macro (the macro declares ClassName's copy constructor and assignment operator as private, so that you cannot use them).

To summarize, QObjects can only be used with reference semantics. In other words, you can pass around references or pointers to QObjects in your application without breaking the single identity constraint.

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
Business & Finance
Computer Science
Language & Literature
Political science