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

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

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

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

The Symbian OS classeshave been written and maintained by those with expertise in dealingwith restricted memory resources, and the classes have been extensively tried and tested as the OS has evolved. While the experience ofwriting your own utility classes and functions is irreplaceable, you getguaranteed efficiency and memory safety from using those provided bySymbian OS.When allocating objects on the heap (and on the stack as describedin the following section), the lifetime of the object is fundamental.

OnSymbian OS, programs may run for months and the user may rarely resettheir phone. For this reason, objects should be cleaned up as soon as theiruseful lifetime ends – whether normally or because of an error condition.You should consider the lifetime of temporary objects allocated on theheap and delete them as soon as they have served their purpose.

Ifyou retain them longer than is necessary, the RAM consumption of theapplication may be higher than necessary.Of course, there’s often a trade-off between memory usage and speed.For example, you may decide to conserve memory by creating an object2The RArray- and CArray-derived container classes take a granularity value onconstruction which is used to allocate space for the array in blocks, where the granularityindicates the number of objects in a block. Your choice of granularity must be consideredcarefully because, if you over-estimate the size of a block, the additional memory allocatedwill be wasted. For example, if a granularity of 20 is specified, but the array typicallycontains only five objects, then the space reserved for 15 objects will be wasted. Of course,you should also be careful not to under-estimate the granularity required, otherwise frequentreallocations will be necessary.

Chapter 7 discusses the use of the Symbian OS containerclasses in more detail.322GOOD CODE STYLEonly when necessary, and destroying it when you’ve finished with it.However, if you need to use it more than once, you will reduce speedefficiency by duplicating the effort of instantiating it. On these occasions,individual circumstances will dictate whether you use the memory andcache the object or take the speed hit and create it only when youneed it, destroying it afterwards. There is some middle ground, though:you may prefer not to instantiate the object until its first use and thencache it.Once you have deleted any heap-based object, you should set thepointer to NULL3 to prevent any attempt to use it or delete it again.However, you don’t need to do this in destructor code: when memberdata is destroyed in a destructor, no code will be able to re-use it becauseit drops out of scope when the class instance is deleted.In the following example, don’t worry too much about the detailsof class CSwipeCard or the two security objects it owns, iPasswordand iPIN.

However, consider the case where a CSwipeCard objectis stored on the cleanup stack and ChangeSecurityDetailsL() iscalled upon it. First the two current authentication objects are deleted,then a function is called to generate new PIN and password objects.If this function leaves, the cleanup stack will destroy the CSwipeCardobject.

As you can see from the destructor, this will call delete oniPIN and iPassword – consider what would happen if I had not seteach of these values to NULL. The destructor would call delete onobjects that had already been destroyed, which isn’t a safe thing to do:the result is undefined, though in debug builds of Symbian OS it willcertainly raise a panic (USER 44). Note that I’ve not set the pointers toNULL in the destructor – as I mentioned above, at this point the object isbeing destroyed, so no further access will be made to those pointers.

It’ssafe to call delete on a NULL pointer, so setting the deleted pointer toNULL after deletion prevents an unnecessary panic if the method whichcreates the new PIN and password objects leaves.ChangeSecurityDetailsL() is also called from ConstructL(),at which point the iPIN and iPassword pointers are NULL (becausethe CBase parent class overloads operator new to zero-fill the object’smemory on creation, as I described in Chapter 1).class CPIN;class CPassword;class CSwipeCard : public CBase{3As an aside: in debug builds of Symbian OS, when a heap cell is freed, the contentsare set to 0xDE. If you are debugging and spot a pointer to 0xDEDEDEDE, the contents havebeen deleted but the pointer has not been NULLed.

Any attempt to use this pointer willresult in a panic.USE HEAP MEMORY CAREFULLY323public:∼CSwipeCard();void ChangeSecurityDetailsL();static CSwipeCard* NewLC(TInt aUserId);private:CSwipeCard(TInt aUserId);void ConstructL();void MakePasswordAndPINL();private:TInt iUserId;CPIN* iPIN;CPassword* iPassword;};CSwipeCard::CSwipeCard(TInt aUserId): iUserId(aUserId) {}CSwipeCard::∼CSwipeCard(){delete iPIN; // No need to NULL the pointersdelete iPassword;}CSwipeCard* CSwipeCard::NewLC(TInt aUserId){CSwipeCard* me = new (ELeave) CSwipeCard(aUserId);CleanupStack::PushL(me);me->ConstructL();return (me);}void CSwipeCard::ConstructL(){ChangeSecurityDetailsL(); // Initializes the object}void CSwipeCard::ChangeSecurityDetailsL(){// Destroy original authentication objectdelete iPIN;// Zero the pointer to prevent accidental re-use or double deletioniPIN = NULL;delete iPassword;iPassword = NULL;MakePasswordAndPINL(); // Create a new random PIN and password}An alternative, slightly more complex, implementation of ChangeSecurityDetailsL() could create the new PIN and password data intemporary descriptors before destroying the current iPIN and iPassword members.

If either allocation fails, the state of the CSwipeCardobject is retained – whereas in the implementation above, if MakePasswordAndPINL() leaves, the CSwipeCard object is left in an uninitialized state, having no password or PIN values set. The choice ofimplementation is usually affected by what is expected to happen ifChangeSecurityDetailsL() leaves.324GOOD CODE STYLEvoid CSwipeCard::ChangeSecurityDetailsL() // Alternative implementation{// MakePasswordAndPINL() has been split into two for simplicityCPIN* tempPIN = MakePINL(); // Create a temporary PINCleanupStack::PushL(tempPIN);CPassword* tempPassword = MakePasswordL();CleanupStack::PushL(tempPassword);delete iPIN;// No need to NULL these, nothing can leavedelete iPassword; // before they are resetiPIN = tempPIN;iPassword = tempPassword;CleanupStack::Pop(2, tempPIN); // Owned by this (CSwipeCard) now}Finally in this section on memory efficiency, it’s worth mentioning thatyou should avoid allocating small objects on the heap.

Each allocationis accompanied by a heap cell header which is four bytes in size, so it’sclear that allocating a single integer on the heap will waste space, as wellas having an associated cost in terms of speed and heap fragmentation. Ifyou do need a number of small heap-based objects, it is best to allocatea single large block of memory and use it to store objects within an array.Degrade Gracefully – Leave if Memory Allocation Is UnsuccessfulYou should code to anticipate low memory or other exceptional conditions.

To save you coding a check that each and every heap allocationyou request is successful, Chapter 2 describes the overload of operatornew which leaves if there is insufficient heap memory for the allocation.Leaves are the preferred method of coping with exceptional conditionssuch as low memory on Symbian OS. When a memory failure occursand causes your code to leave, you should have a higher level TRAP to”catch” the failure and handle it gracefully (for example, by freeing somememory, closing the application, notifying the user, or whatever seemsmost appropriate).Symbian OS runs on limited-resource mobile phones which will, attimes, run out of memory.

So you must prepare your code to cope underthese conditions. To help you verify that your code performs safely underlow memory conditions, Symbian OS provides a variety of test tools andmacros that you can use in your own test code to simulate low memoryconditions. I described these in detail in Chapter 17.Check that Your Code Does not Leak MemoryI’ve already discussed how to prevent memory leaks, but, of course, thisdoesn’t mean that they won’t occur.

It is important to test your coderegularly to check that it is still leave-safe and that no leaks have beenintroduced by maintenance or refactoring. Symbian OS provides macrosand test tools to test the heap integrity and to show up leaks when yourUSE STACK MEMORY CAREFULLY325code unloads. I describe how to use these in Chapter 17. Leaks can bedifficult to track down, so it is far easier to test for them as part of theregular testing cycle, in order to catch regressions close to the time atwhich they are introduced.21.3 Use Stack Memory CarefullyFor a target mobile phone running Symbian OS, the program stacksize defaults to 8 KB,4 and it doesn’t grow when that size is exceeded.Actually that’s not quite true, because the Symbian OS emulator runningon Windows will extend the program stack if the size exceeds the limit.Consequently, you may find that your application runs perfectly well onthe emulator, while it overflows the stack on hardware.So what happens when you outgrow the stack space available? Furtherattempts to use the stack will result in access to a memory address that’snot mapped into the address space for your process.

This causes an accessviolation that will generate an exception – at which point the kernel willpanic your code with KERN-EXEC 3. In fact, if you try to build codewhere any single function tries to allocate automatic variables occupyingmore than 4 KB, you will receive an unresolved external __chkstk linkerror. However, this only considers static allocation and doesn’t take intoaccount recursion, variable length looping or anything else that can onlybe calculated at runtime.Both the size of the program stack, which is significantly smaller thanmost desktop applications have available, and the fact it does not growdynamically, make it important that your stack usage is conservative.Manage Recursive Code CarefullyRecursive code can use significant amounts of stack memory.

To ensurethat your code does not overflow the stack, you should build in a limit tothe depth of recursion, where this is possible. It’s a good idea to minimize4For a component running in a separate process, e.g. a server or .exe, you can changethe stack size from the default 8 KB, by adding the following to your. mmp file to specify anew stack size in hexadecimal or decimal format. For example:epocstacksize 0x00003000 // 12 KBAlternatively, you can create a new thread and specify a chosen stack size, as describedin Chapter 10. This is particularly useful if your application makes heavy use of the stack,say through recursion, and needs more space than the default stack size makes available.If you do hit the limit, it’s worth considering why your code is using so much stackspace before assigning more, because consumption of extra stack resources leaves less freefor other programs.

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

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

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

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