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

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

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

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

If any of the functions leaves, theobject must be returned to its original state.Alternatively, you can do this by putting a TRAP harness around eachcall that may leave, rolling back any previous changes when the TRAP”catches” a leave. Consider the following example code where an atomicmethod, UpdateSpreadsheetL(), calls two separate leaving functionsinside TRAPs to recalculate the contents of a spreadsheet and update theview of the spreadsheet. If either of the methods leaves, the TRAPs catchthe leave and allow the state of the spreadsheet and the spreadsheet viewto be returned to the point before the UpdateSpreadSheetL() methodwas invoked, by calling Rollback().class CSpreadSheet : public CBase{public:// Guarantees an atomic updatevoid UpdateSpreadSheetL(const CUpdate& aUpdate);...

// Other methods omittedprivate:// Recalculates the contents of iSpreadSheetvoid RecalculateL(const CData& aData);void UpdateL();// Updates iSpreadSheetViewvoid RollBack(); // Reverts to the previous stateprivate:CExampleSpreadSheet* iSpreadSheet;// Defined elsewhereCExampleSpreadSheetView* iSpreadSheetView; // Defined elsewhereUSING TCleanupItem FOR CUSTOMIZED CLEANUP45...};void CSpreadSheet::UpdateSpreadSheetL(const CUpdate& aUpdate){TRAPD(result, RecalculateL(aData)); // Performs the recalculationif (KErrNone==result)// if no error, update the view{TRAP(result, UpdateL());}if (KErrNone!=result) // RecalculateL() or UpdateL() failed{// Undo the changesRollBack();User::Leave(result);}}However, as I’ve described, the use of TRAPs has an associatedcost in terms of less efficient and more complex code.

A preferabletechnique is to modify the code which reverts the object to its previous state. In the following example, the Rollback() method is nowstatic and takes a TAny* pointer – and can be used to initialize aTCleanupItem. Rollback() casts the incoming TAny* to CSpreadSheet* and calls DoRollBack(), which returns the spreadsheet to itsstate before UpdateSpreadSheetL() was called.class CSpreadSheet : public CBase{public:// Guarantees an atomic updatevoid UpdateSpreadSheetL(const CUpdate& aUpdate);...

// Other methods omittedprivate:// Recalculates the contents of iSpreadSheetvoid RecalculateL(const CData& aData);void UpdateL(); // Updates iSpreadSheetView// Reverts to the previous statestatic void RollBack(TAny* aSpreadSheet);void DoRollBack();private:CExampleSpreadSheet* iSpreadSheet;CExampleSpreadSheetView* iSpreadSheetView;...};void CSpreadSheet::UpdateSpreadSheetL(const CUpdate& aUpdate){// Initialize the TCleanupItemTCleanupItem cleanup(CSpreadSheet::RollBack, this);CleanupStack::PushL(cleanup); // Put it on the cleanup stackRecalculateL(aData);UpdateL();CleanupStack::Pop(&cleanup);// TCleanupItem is no longer required}46THE CLEANUP STACKvoid CSpreadSheet::Rollback(TAny* aSpreadSheet){ASSERT(aSpreadSheet);CSpreadSheet* spreadsheet = static_cast<CSpreadSheet*>(aSpreadSheet);spreadsheet->DoRollBack();}3.5 PortabilityThe cleanup stack is a concept specific to Symbian OS, which means thatcode that uses it is non-portable.

Sander van der Wal of mBrain Softwarehas proposed using the cleanup stack to implement auto_ptr<>, partof the C++ standard, for Symbian OS, to make cleanup code moretransferable. The auto_ptr<> template class can be used for automaticdestruction, even when an exception is thrown and use of this standardcleanup mechanism could certainly allow code to be ported more rapidly.You can find more information about the implementation through linkson the Symbian Developer Network (www.symbian.com/developer),where you can also find additional, in-depth articles about cleanup onSymbian OS.3.6 An Incidental Note on the Use of CastsC++ supports four cast operators (static_cast, const_cast, reinterpret_cast and dynamic_cast) which are preferable to the oldC-style cast because they each have a specific purpose which the compiler can police for erroneous usage.

For this reason, when you need to usea cast in Symbian OS code, you should endeavor to use static_cast,const_cast or reinterpret_cast rather than a basic C-style cast.Another benefit of using these casts is that they are more easily identified,both by the human eye and by search tools like grep.Prior to Symbian OS v6.0, GCC did not support the C++ castingoperators. Instead, Symbian OS defined a set of macros that simply usedC-style casts for that compiler but at least allowed Symbian OS code todifferentiate between the casts. The macros made the use of casts visibleand allowed the code to be upgraded easily when the GCC compilerbegan to support the new casts, from v6.0 onwards.

The macros werechanged to reflect the availability of the new casts in v6.1.You may encounter legacy code which still uses these macros,such as CleanupReleasePushL(), CleanupDeletePushL() andCleanupClosePushL(), but, from v6.0 onwards, you should simplyuse the native C++ casting operators rather than these macros.SUMMARY47You’ll find the legacy macros defined in e32def.h:#define CONST_CAST(type,exp) (const_cast<type>(exp))#define STATIC_CAST(type,exp) (static_cast<type>(exp))#define REINTERPRET_CAST(type,exp) (reinterpret_cast<type>(exp))#if defined(__NO_MUTABLE_KEYWORD)#define MUTABLE_CAST(type,exp) (const_cast<type>(exp))#else#define MUTABLE_CAST(type,exp) (exp)#endifYou’ll notice that dynamic_cast is not supported on Symbian OS.This cast is useful, allowing you to perform a safe cast from pointers of lessderived classes to those in the inheritance hierarchy that are either morederived (child classes) or related across the inheritance tree. However,dynamic_cast makes use of runtime type identification (RTTI) which isnot supported on Symbian OS because of the expensive runtime overheadrequired.4 For this reason, dynamic_cast is, sadly, not supported bySymbian OS.3.7 SummaryThis chapter covered one of the most fundamental concepts of SymbianOS, the cleanup stack.

It first explained the need for the cleanup stack,to prevent inadvertent heap memory leaks in the event of a leave. It thenmoved on to illustrate how, and how not, to use the cleanup stack mosteffectively. The chapter discussed the advantages of the cleanup stackover a TRAP harness, which can be used to prevent leaves but has a moresignificant impact on run-time speed and code size.The chapter discussed in detail how the cleanup stack actually worksand concluded by describing how it can best be used to ensure cleanupin the event of a leave for C class and R class objects, T class objects onthe heap and objects referenced by M class interface pointers.You can find more information about leaves in Chapter 2; the impactof leaves on constructor code is discussed in the next chapter.4Another useful feature of dynamic_cast is that you can tell whether the castsucceeded; it will return a NULL pointer if you’re casting a pointer or throw an exception ifyou’re casting a reference.

As you’ll know from the previous chapter, Symbian OS does notsupport C++ exceptions, and uses leaves instead. This also contributes to the reason whydynamic_cast is unavailable on Symbian OS.4Two-Phase ConstructionEither that wallpaper goes, or I doReputed to be the last words of Oscar WildeBy now, you’ll have gathered that Symbian OS takes memory efficiencyvery seriously indeed.

It was designed to perform well on devices withlimited memory, and uses memory management models such as thecleanup stack to ensure that memory is not leaked, even under errorconditions or in exceptional circumstances.Two-phase construction is an idiom that you’ll see used extensively inSymbian OS code. To understand why it is necessary, we must considerexactly what happens when you create an object on the heap.

Considerthe following line of code, which allocates an object of type CExampleon the heap, and sets the value of the foo pointer accordingly:CExample* foo = new CExample();The code calls the new operator, which allocates a CExample objecton the heap if there is sufficient memory available. Having done so, itcalls the constructor of class CExample to initialize the object.As I described in Chapter 3, once you have a heap object such asthat pointed to by foo, you can use the cleanup stack to ensure that theCExample object is correctly cleaned up in the event of a leave. But itis not possible to do so inside the new operator between allocation ofthe object and invocation of its constructor.

If the CExample constructoritself leaves, the memory already allocated for the object and any memorythe constructor may have allocated will be orphaned. This gives rise toa key rule of Symbian OS memory management: no code within a C++constructor should ever leave.Of course, to initialize an object you may need to write code thatleaves, say to allocate memory or read a configuration file which maybe missing or corrupt.

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

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

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

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