Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 23

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 23 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 232018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 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.

Характеристики

Тип файла
PDF-файл
Размер
2,53 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6353
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее