The Symbian OS (779886), страница 21

Файл №779886 The Symbian OS (Symbian Books) 21 страницаThe Symbian OS (779886) страница 212018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

(It is important that construction succeeds, since only then can theobject’s destructor be called; if the destructor cannot be called, memorymay have been leaked [Stroustrup 1993, p. 311].) Again, a number ofsystem functions are available to regularize the pattern and take careof underlying details for developers. (In its earliest implementation, twophase construction was matched by two-phase destruction.

The eventualconsensus was that this was an idiom too far.)19See [Stichbury 2005, p. 14] for a detailed explanation.See the discussion in [Harrison 2003, p. 150]. This is the authoritative programmers’guide.20SYMBIAN OS IDIOMS77Charles Davies:We had an ethic that said that memory leakage was something the programmerwas expected to manage. So something like the Window Server, which mightbe running for a year at a time, needed to make sure that if an exception wascalled it didn’t leak memory. The cleanup stack was an invention to make iteasier for people to do that. You’d have an event loop, and at the high endof the event loop you’d push things on the stack that needed to be unwound,whether they were files that needed to be closed or objects that needed to bedestroyed. That was a pragmatic thing, you know.

‘Let’s provide somethingthat encourages well-written applications from the point of view of memoryleakage.’Cleanup is pervasive in the system ([Harrison 2003, p. 135]), permeating every line of code a developer writes, or reads, in Symbian OS, withits highly visible trailing ‘L’ naming convention, its Leave() methodsand TRAPs, and its cleanup stack push and pop calls.For new developers, it is both highly visible and immediately unfamiliar, which leads to an immediate impression that the code is both strangeand difficult. However, the conventions are not intrinsically difficult,even if the discipline may be.

The purpose is equally straightforward:to manage run-time resource failures. On a small device, memory mayrapidly get filled up by the user (whether by loading a massive image,downloading too many MP3s, or simply taking more pictures or videoclips than the device has room for). Other resources, whether USB cableconnections, infrared links, phone network signals, or removable mediacards, can simply disappear without warning at any time.

Mostly thesehazards simply do not exist on desktop systems. On phones, they are thenorm.Martin Tasker:I think the cleanup stack was a brilliant solution to the problem that we werefaced with at the time.DescriptorsDescriptors are the Symbian OS idiom for safe strings. (‘Safe’ meansboth type safe and memory safe and compares with C++ native C-stylestrings, which are neither21 ) Descriptors were invented (by Colly Myers)because there was no suitable C++ library class, or none that was readilyavailable.21Nor are Java or Microsoft Foundation Class strings for that matter, according to[Stichbury 2005, p.

55].78INTRODUCTION TO THE ARCHITECTURE OF SYMBIAN OSIn principle, descriptors simply wrap character-style data and includelength encoding and overrun checking. (Descriptors are not terminatedby NULL; they encode their length in bytes into their header, and refuseto overrun their length.) As well as this basic behavior they also providesupporting methods for searching, matching, comparison and sorting.Descriptors support two ‘widths’, that is, 8-bit or 16-bit characters,based on C++ #define (typedef) and originally designed to enable acomplete system build to be switched, more or less with a single definition, between ASCII-based and Unicode-based character text support.More interestingly, descriptors also support modifiable and unmodifiable variants and stack- and heap-based variants.

The content ofunmodifiable (constant) descriptors cannot be altered, although it canbe replaced, whereas that of modifiable descriptors can be altered, up tothe size with which the descriptor was constructed.22Another important distinction is between buffer and pointer descriptor classes.

Buffer descriptors actually contain data, whereas pointerdescriptors point to data stored elsewhere (typically either in a bufferor a literal). A pointer descriptor, in other words, does not contain itsown data. A final distinction is between stack-based and heap-basedbuffer descriptors. Stack-based descriptors are relatively transient andshould be used for small strings because they are created directly on thestack (a typical use is to create a file name, for example. Heap-baseddescriptors, on the other hand, are intended to have longer durationand are likely to be shared through the run-time life of a program (seeTable 3.1).23Table 3.1 Descriptor classes.ConstantModifiablePointerTPtrCTPtrBuffer (stack-based)TBufCTBufHeap-basedHBufCSee [Harrison 2003, p.

123] for a fuller explanation of the descriptorclasses.22Although modifiable, once allocated there is no further memory allocation for adescriptor, so its physical length cannot be extended. For example, to append new contentto a descriptor requires that there is already room within the descriptor for the data to beappended.23[Stitchbury 2005] contains a good overview.SYMBIAN OS IDIOMS79Descriptors differ from simple literals, which are defined as constantsusing the LIT macro, in that they are dynamic (literals are created atcompile time, descriptors are not). A typical use of a pointer descriptor isto point to a literal.Martin Tasker:The 8-bit/16-bit aspect was ASCII versus Unicode, though, in retrospect weshould have been braver about adopting Unicode straight away.

But bear inmind that the ARM 3 instruction set we were then using didn’t have any 16-bitinstructions or, more accurately, it didn’t have any instructions to manipulate16-bit data types, so it was not efficient to use Unicode at that time. But maybewe should have had more foresight and courage, because it turned out to bea distraction. But as a kind of memory buffer, I think they were reasonablydistinctive.Given the state of the art at the time, Peter Jackson believes that thedistinction between 8-bit and 16-bit was understandable but that a morenaturally object-oriented approach would have been preferable.Peter Jackson:I think it would have been more elegant to have a descriptor that knewinternally what kind of descriptor it was, whether it was the 8-bit or 16bit variant. I never liked the fact that some of these things were done bymacros.Descriptors are not only type safe, they are memory safe, making memory overflow (‘out-of-bounds’ behavior) impossible.

Descriptor methodswill panic if an out-of-bounds attempt is detected (see Figure 3.1).TDesCTBufCBaseTPtrCTBufCTDesHBufCTPtrFigure 3.1 Descriptor class hierarchyTBuf80INTRODUCTION TO THE ARCHITECTURE OF SYMBIAN OSCharles Davies:Descriptors were Colly Myers’s thing, definitely, and the idea was ratherlike the cleanup stack, to stop people doing memory overwrites. That’s abig protection against worms and other attacks, deliberate and maliciousoverwriting of the heap, although at the time that wasn’t the driving reason todo it. We did it to stop programmers making mistakes.C and T and Other ClassesAs well as the use of the trailing ‘L’ (for ‘leaving’) and ‘C’ (for ‘constant’)to flag properties of methods, Symbian OS also uses some similarlystraightforward class-naming conventions to flag fundamental propertiesof classes.Martin Tasker:If you look at the C and T types, they offer a very, very simple guide tothe programmer as to how to use these types.

They are as simple as Java’sobjects and built-ins. We don’t do garbage collection because C++ doesn’t dogarbage collection, so we have to cope with that. We have to do it manually,but otherwise I think our conventions are as simple as Java.The most important naming conventions are summarized as follows: 24• T classes are simple types which require no destructor and behavelike C++ built-in types.• C classes derive from CBase and should always be explicitly constructed, thus ensuring that they are always allocated on the heap.CBase classes also therefore require explicit destruction.

CBase provides a basic level of additional support, including a virtual destructor,allowing CBase-derived objects to be deleted through the CBasepointer and performing cleanup stack housekeeping. CBase alsooverloads operator new to zero-initialize an object when it is firstallocated on the heap. All member data of derived classes is thereforeguaranteed to be zero on initialization.• R classes indicate resource classes, typically a client session handle fora server session. Since an R class typically contains only a handle, itdoes not require either construction or destruction. R classes thereforemay safely be either automatics or class members.24[Stichbury 2005, Chapter 1] provides a comprehensive discussion.SYMBIAN OS IDIOMS81• M classes are ‘mixin’ classes (abstract interface classes), the only formin which multiple inheritance is supported in Symbian OS.• Descriptors are immediately recognizable as either TPtr pointerdescriptors, or TBuf (stack-based) or HBufC (heap-based) bufferdescriptors.Manifest ConstantsSymbian OS uses manifest constants – implemented as typedefs, thatis, system-defined types – instead of the native types supported by astandard C++ compiler on standard hardware.

This is partly, of course,because the cross-development model means that the eventual intendedtarget platform is not the same as the development platform, hence the‘native’ types of the platform on which the code is compiled may differfrom those of the platform on which it is intended to run. The use oftype definitions also has its roots in designing to support both ASCII andUnicode builds, which is now superfluous since Symbian OS has beenall-Unicode since before v6.Supporting emulator builds (that is, running Symbian OS programs onPC as well as ARM, and not just developing on PC) creates the additionalcomplexity of requiring not one supported compiler but two (or more);originally Microsoft compilers were specified for emulator builds andGCC for ARM. More recently Metrowerks and Borland compilers havebeen supported and, in Symbian OS v9, ARM’s RVCT replaces GCCas the ‘official’ ARM target compiler (although GCCE is still supportedto ensure a low-cost development option).

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

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

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

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