Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 23
Текст из файла (страница 23)
The ”R” of an R class indicates that it owns aresource, which in the case of these classes is the heap memory allocatedto hold the array.98DYNAMIC ARRAYS AND BUFFERSRArray objects themselves may be either stack- or heap-based. Aswith all R classes, when you have finished with an object you must calleither the Close() or Reset() function to clean it up properly, that is,to free the memory allocated for the array.
RArray::Close() frees thememory used to store the array and closes it, while RArray::Reset()frees the memory associated with the array and resets its internal state,thus allowing the array to be reused. It is acceptable just to call Reset()before allowing the array object to go out of scope, since all the heapmemory associated with the object will have been cleaned up.RArray<class T> comprises a simple array of elements of the samesize.
To hold the elements it uses a flat, vector-like block of heapmemory, which is resized when necessary. This class is a thin templatespecialization of class RArrayBase.RPointerArray<class T> is a thin template class deriving fromRPointerArrayBase. It comprises a simple array of pointer elementswhich again uses flat, linear memory to hold the elements of the array,which should be pointers addressing objects stored on the heap. Youmust consider the ownership of these objects when you have finishedwith the array. If the objects are owned elsewhere, then it is sufficientto call Close() or Reset() to clean up the memory associated withthe array. However, if the objects in the array are owned by it, theymust be destroyed as part of the array cleanup, in a similar mannerto the previous example for CArrayPtrSeg. This can be effected bycalling ResetAndDestroy() which itself calls delete on each pointerelement in the array.RArrayRPointerArrayBaseAppend()Insert()Remove()Find()At()...TAny* iEntriesAppend()Insert()Remove()Find()At()...TAny* iEntriesTTRArrayRPointerArraySee e32std.hfor further detailsFigure 7.3Inheritance hierarchy of RArray<T> and RPointerArray<T>RArray<class T> AND RPointerArray<class T>99The RArray and RPointerArray classes are shown in Figure 7.3.They provide better searching and ordering than their CArrayX counterparts.
The objects contained in RArray and RPointerArray maybe ordered using a comparator function provided by the element class.That is, objects in the array supply an algorithm which is used to orderthem (typically implemented in a function of the element class) wrappedin a TLinearOrder<class T> package. It is also possible to performlookup operations on the RArray and RPointerArray classes in asimilar manner. The RArray classes have several Find() methods, oneof which is overloaded to take an object of type TIdentityRelation<class T>. This object packages a function, usually provided bythe element class, which determines whether two objects of type T match.There are also two specialized classes defined specifically for arraysof 32-bit signed and unsigned integers, RArray<TInt> and RArray<TUint> respectively.
These use the TEMPLATE_SPECIALIZATION macro to generate type-specific specializations over the genericRPointerArrayBase base class. The classes have a simplified interface, compared to the other thin template classes, which allows them todefine insertion methods that do not need a TLinearOrder object andlookup methods that do not require a TIdentityRelation.To illustrate how to use the RArray<class T> class, let’s look atsome example code. I’ve modified the CTaskManager class I usedpreviously to use an RArray to store the TTask objects. First, here’s theTTask class, which I’ve modified to add a priority value for the task, andfunctions for comparison and matching; where the code is identical tothe previous example I’ve omitted it.class TTask // Basic T class, represents a task{public:TTask(const TDesC& aTaskName, const TInt aPriority);...public:static TInt ComparePriorities(const TTask& aTask1,const TTask& aTask2);static TBool Match(const TTask& aTask1, const TTask& aTask2);private:TBuf<10> iTaskName;TInt iPriority;};TTask::TTask(const TDesC& aTaskName, const TInt aPriority): iPriority(aPriority){iTaskName.Copy(aTaskName);}// Returns 0 if both are equal priority,// Returns a negative value if aTask1 > aTask2// Returns a positive value if aTask1 < aTask2TInt TTask::ComparePriorities(const TTask& aTask1, const TTask& aTask2){if (aTask1.iPriority>aTask2.iPriority)100DYNAMIC ARRAYS AND BUFFERSreturn (-1);else if (aTask1.iPriority<aTask2.iPriority)return (1);elsereturn (0);}// Compares two tasks; returns ETrue if both iTaskName and// iPriority are identicalTBool TTask::Match(const TTask& aTask1, const TTask& aTask2){if ((aTask1.iPriority==aTask2.iPriority) &&(aTask1.iTaskName.Compare(aTask2.iTaskName)==0)){return (ETrue);}return (EFalse);}Here’s the task manager class, which has changed slightly becauseI’m now using RArray<TTask> rather than CArrayPtrSeg<TTask>to hold the set of tasks.
Again, where the code is unchanged from theearlier example, I’ve omitted it for clarity.class CTaskManager : public CBase// Holds a dynamic array of TTask pointers{public:static CTaskManager* NewLC();∼CTaskManager();public:void AddTaskL(TTask& aTask);void InsertTaskL(TTask& aTask, TInt aIndex);void RunAllTasksL();void DeleteTask(TInt aIndex);void DeleteTask(const TTask& aTask);public:inline TInt Count() {return (iTaskArray.Count());};inline TTask& GetTask(TInt aIndex) {return(iTaskArray[aIndex]);};private:CTaskManager() {};private:RArray<TTask> iTaskArray;};CTaskManager::∼CTaskManager(){// Close the array (free the memory associated with the entries)iTaskArray.Close();}void CTaskManager::AddTaskL(TTask& aTask){// Add a task to the end of arrayUser::LeaveIfError(iTaskArray.Append(aTask));}void CTaskManager::InsertTaskL(TTask& aTask, TInt aIndex)RArray<class T> AND RPointerArray<class T>101{// Insert a task in a given elementUser::LeaveIfError(iTaskArray.Insert(aTask, aIndex));}void CTaskManager::RunAllTasksL(){// Sorts the tasks into priority order then iterates through them// and calls ExecuteTaskL() on each// Construct a temporary TLinearOrder object implicitly – the// equivalent of the following:// iTaskArray.Sort(TLinearOrder<TTask>(TTask::ComparePriorities));iTaskArray.Sort(TTask::ComparePriorities);TInt taskCount = iTaskArray.Count();for (TInt index = 0; index < taskCount; index++){iTaskArray[index].ExecuteTaskL();}}void CTaskManager::DeleteTask(const TTask& aTask){// Removes all tasks identical to aTask from the array// Constructs a temporary TIdentityRelation object implicitly – the// equivalent of the following:// TInt foundIndex = iTaskArray.Find(aTask,//TIdentityRelation<TTask>(TTask::Match));while (TInt foundIndex = iTaskArray.Find(aTask,TTask::Match)! =KErrNotFound){iTaskArray.Remove(foundIndex);}}void CTaskManager::DeleteTask(TInt aIndex){// Removes the task at index aIndex from the arrayiTaskArray.Remove(aIndex);}You’ll notice the following changes:• The calls to add and insert elements are within User::LeaveIfError() because those methods in RArray do not leave but insteadreturn an error if a failure occurs (for example, if there is insufficientmemory available to allocate the required space in the array).• CTaskManager::RunAllTasks() sorts the array into descendingpriority order before iterating through the tasks and calling ExecuteTaskL() on each.• CTaskManager has an extra method that deletes all elements fromthe array where they are identical to the one specified: DeleteTask(const TTask& aTask).
This function uses the Find() function to match each element in the array against the task specified,deleting any it finds that are identical. Note that this functioncannot leave.102DYNAMIC ARRAYS AND BUFFERSHere’s the modified version of code that uses the task manager class. Itis quite similar to the previous code because the change to the encapsulated array class – which stores the tasks in CTaskManager – does notaffect it:void TestTaskManagerL(){CTaskManager* taskManager = CTaskManager::NewLC();// Add tasks to the array, use the index to set the task priority_LIT(KTaskName, "TASKX%u");for (TInt index=0; index<4; index++){TBuf<10> taskName;taskName.Format(KTaskName, index);TTask task(taskName, index);taskManager->AddTaskL(task);}ASSERT(4==taskManager->Count());// Add a copy of the task at index 2// to demonstrate sorting and matchingTBuf<10> taskName;taskName.Format(KTaskName, 2);TTask copyTask(taskName, 2);taskManager->AddTaskL(copyTask);ASSERT(5==taskManager->Count());taskManager->RunAllTasksL();// Remove both copies of the tasktaskManager->DeleteTask(copyTask);ASSERT(3==taskManager->Count());// Destroy the taskManagerCleanupStack::PopAndDestroy(taskManager);}7.3 Why Use RArray Instead of CArrayX?The original CArrayX classes use CBufBase, which allows a varieddynamic memory layout for the array using either flat or segmented arraybuffers.
However, CBufBase works with byte buffers and requires aTPtr8 object to be constructed for every array access. This results ina performance overhead, even for a simple flat array containing fixedlength elements. Furthermore, for every method which accesses the array,there are a minimum of two assertions to check the parameters, even inrelease builds.DYNAMIC DESCRIPTOR ARRAYS103For example, to access a position in a CArrayFixX array, operator[] calls CArrayFixBase::At(), which uses an __ASSERT_ALWAYS statement to range-check the index and then callsCBufFlat::Ptr() which also asserts that the position specified lieswithin the array buffer.