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

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

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

Текст из файла (страница 12)

In consequence, if your heap-based classdoes not inherit from CBase, directly or indirectly, and you push it ontothe cleanup stack, its destructor is not called and it may not be cleanedup as you expect.The CleanupStack::PushL(TAny*) overload is used when youpush onto the cleanup stack a pointer to a heap-based object which doesnot have a destructor, for example, a T class object or a struct whichhas been allocated, for some reason, on the heap. Recall that T classes donot have destructors, and thus have no requirement for cleanup beyonddeallocation of the heap memory they occupy.Likewise, when you push heap descriptor objects (of class HBufC,described in Chapters 5 and 6) onto the cleanup stack, the CleanupStack::PushL(TAny*) overload is used.

This is because HBufCobjects are, in effect, heap-based objects of a T class. Objects of typeHBufC require no destructor invocation, because they only contain plainbuilt-in type data (a TUint representing the length of the descriptorand a character array of type TText8 or TText16). The only cleanupnecessary is that required to free the heap cells for the descriptor object.The third overload, CleanupStack::PushL(TCleanupItem),takes an object of type TCleanupItem, which allows you to putother types of object or those with customized cleanup routines ontothe cleanup stack. A TCleanupItem object encapsulates a pointer tothe object to be stored on the cleanup stack and a pointer to a functionthat provides cleanup for that object.

The cleanup function can be a localfunction or a static method of a class.For reference, here’s the definition of the TCleanupItem class andthe required signature of a cleanup function, which takes a single TAny*parameter and returns void:// From e32base.htypedef void (*TCleanupOperation)(TAny*);//class TCleanupItem{public:40THE CLEANUP STACKinline TCleanupItem(TCleanupOperation anOperation);inline TCleanupItem(TCleanupOperation anOperation, TAny* aPtr);private:TCleanupOperation iOperation;TAny* iPtr;friend class TCleanupStackItem;};A call to PopAndDestroy() or leave processing removes the objectfrom the cleanup stack and calls the cleanup function provided by theTCleanupItem.class RSample{public:static void Cleanup(TAny *aPtr);void Release();... // Other member functions omitted for clarity};// cleanup functionvoid RSample::Cleanup(TAny *aPtr){// Casts the parameter to RSample and calls Release() on it// (error-checking omitted)(static_cast<RSample*>(aPtr))->Release();}void LeavingFunctionL(){RSample theExample;TCleanupItem safeExample(RSample::Cleanup, &theExample);CleanupStack::PushL();// Some leaving operations calledtheExample.InitializeL(); // Allocates the resource...// Remove from the cleanup stack and invoke RSample::Cleanup()CleanupStack::PopAndDestroy();}You’ll notice that the static Cleanup() function defined for RSamplecasts the object pointer it receives to a pointer of the class to be cleanedup.

This is to allow access to the non-static Release() method whichperforms the cleanup. For code to be generic, the TCleanupItem objectmust store the cleanup pointer and pass it to the cleanup operation as aTAny* pointer.The curious reader may be wondering how the cleanup stack discriminates between a TCleanupItem and objects pushed onto thecleanup stack using one of the other PushL() overloads. The answeris that it doesn’t – all objects stored on the cleanup stack are of typeTCleanupItem.

The PushL() overloads that take CBase or TAnyUSING THE CLEANUP STACK WITH NON-CBase CLASSES41pointers construct a TCleanupItem implicitly and store it on the cleanupstack. As I’ve already described, the cleanup function for the CBase*overload deletes the CBase-derived object through its virtual destructor.For the TAny* overload, the cleanup function calls User::Free(),which simply frees the allocated memory.Symbian OS also provides three utility functions, each of which generates an object of type TCleanupItem and pushes it onto the cleanupstack, for cleanup methods Release(), Delete() and Close().

Thefunctions are templated so the cleanup methods do not have to bestatic.CleanupReleasePushL(T& aRef)Leave processing or a call to PopAndDestroy() will call Release()on an object of type T. To illustrate, here’s the implementation frome32base.inl:// Template class CleanupReleasetemplate <class T>inline void CleanupRelease<T>::PushL(T& aRef){CleanupStack::PushL(TCleanupItem(&Release,&aRef));}template <class T>void CleanupRelease<T>::Release(TAny *aPtr){(STATIC_CAST(T*,aPtr))->Release();}template <class T>inline void CleanupReleasePushL(T& aRef){CleanupRelease<T>::PushL(aRef);}You may be wondering about the use of STATIC_CAST rather thanthe C++ standard static_cast I used in RSample::Cleanup(). Fearnot, I’ll explain why it’s used at the end of this chapter, in Section 3.6(”An Incidental Note on the Use of Casts”).And here’s an example of its use to make an object referred to by an Mclass3 pointer leave-safe.

The M class does not have a destructor; insteadthe object must be cleaned up through a call to its Release() method,which allows an implementing class to customize cleanup:class MExtraTerrestrial // See Chapter 1 for details of mixin classes{public:virtual void CommunicateL() = 0;... // The rest of the interface is omitted for clarityvirtual void Release() = 0;};3M classes are described in more detail in Chapter 1 and define a ”mixin” interfacewhich is implemented by a concrete inheriting class, which will, typically, also derive fromCBase.42THE CLEANUP STACKclass CClanger : public CBase, MExtraTerrestrial{public:static MExtraTerrestrial* NewL();virtual void CommunicateL(); // From MExtraTerrestrialvirtual void Release();private:CClanger();∼CClanger();private:...};void TestMixinL(){MExtraTerrestrial* clanger = CClanger::NewL();CleanupReleasePushL(*clanger); // The pointer is deferenced here...

// Perform actions which may leaveCleanupStack::PopAndDestroy(clanger); // Note pointer to the object}Notice the asymmetry in the calls to push the object onto the cleanupstack and to pop it off again. As you can see from the definition above,CleanupReleasePushL() takes a reference to the object in question,so you must deference any pointer you pass it. However, if you choose toname the object when you Pop() or PopAndDestroy() it, you shouldpass a pointer to the object.

This is because you’re not calling an overloadof Pop().The definition of CleanupClosePushL() is similarly asymmetric,but for CleanupDeletePushL() you should pass in a pointer. This isbecause objects which may be cleaned up using Release() or Close()may equally be CBase-derived heap-based objects, such as the oneshown below, or R class objects which typically reside on the stack, asshown in a later example. As I’ll describe, the CleanupDeletePushL()function should only apply to heap-based objects, so this function has apointer argument.CleanupDeletePushL(T& aRef)Here’s the implementation from e32base.inl:// Template class CleanupDeletetemplate <class T>inline void CleanupDelete<T>::PushL(T* aPtr){CleanupStack::PushL(TCleanupItem(&Delete,aPtr));}template <class T>void CleanupDelete<T>::Delete(TAny *aPtr){delete STATIC_CAST(T*,aPtr);}template <class T>inline void CleanupDeletePushL(T* aPtr){CleanupDelete<T>::PushL(aPtr);}USING THE CLEANUP STACK WITH NON-CBase CLASSES43As you can see, leave processing or a call to PopAndDestroy()calls delete on an object added to the cleanup stack using thismethod.

A call is thus made to the destructor of the object and theheap memory associated with the object is freed. It is similar to usingthe CleanupStack::PushL() overload which takes a CBase pointer,and is useful when an M class-derived pointer must be placed on thecleanup stack.Calling CleanupStack::PushL() and passing in an M class pointerto a heap-based object invokes the overload which takes a TAny*parameter. For this overload, the TCleanupItem constructed does notcall the object’s destructor, as I discussed above.

Instead, it simplyattempts to free the memory allocated for the object and, in doing so,causes a panic (USER 42) because the pointer does not point to the startof a valid heap cell.This is because a concrete class that derives from an M class alsoinherits from another class, for example CBase, or a derived classthereof. The mixin pointer must be the second class in the inheritancedeclaration order if destruction of the object is to occur correctly, throughthe CBase virtual destructor. This means that when you access the objectthrough the M class interface, the pointer has been cast to point at the Mclass sub-object which is some way into the allocated heap cell for theobject.

The memory management code cannot deduce this and panicswhen it cannot locate the appropriate structure it needs to free the cellback to the heap.To resolve this, you should always use CleanupDeletePushL()to push M class pointers onto the cleanup stack, if the M class will becleaned up through a virtual destructor.

This creates a TCleanupItemfor the object which calls delete on the pointer, using its destructor tocleanup the object correctly.CleanupClosePushL(T& aRef)If an object is pushed onto the cleanup stack using CleanupClosePushL(), leave processing or a call to PopAndDestroy() callsClose() on it. As an example, it can be used to make a stack-basedhandle to the file server leave-safe, closing it in the event of a leave:void UseFilesystemL(){RFs theFs;User::LeaveIfError(theFs.Connect());CleanupClosePushL(theFs);... // Call functions which may leaveCleanupStack::PopAndDestroy(&theFs);}44THE CLEANUP STACKCleanupStack::PushL(TAny*) is used to push a pointer toa heap-based object which does not have a destructor onto thecleanup stack (for example, a T class object or a struct).CleanupStack::PushL(TCleanupItem) allows you to putother types of object, such as those with customized cleanuproutines, onto the cleanup stack.

Symbian OS provides three templated utility functions, each of which generates an object oftype TCleanupItem and pushes it onto the cleanup stack, forRelease(), Delete() and Close() cleanup methods.3.4 Using TCleanupItem for Customized CleanupAs I’ve already mentioned, TCleanupItem can be used to perform customized cleanup when a leave occurs. The cleanup function (TCleanupOperation) used by the TCleanupItem must be of the correctsignature (void Function(TAny* aParam)) and may perform anycleanup action appropriate in the event of a leave. It is especially usefulfor transaction support where a sequence of functions must either succeedor fail as a single atomic operation.

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

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

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

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