quick_recipes (779892), страница 10

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

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

for an Append() operationmyRBuf.CleanupClosePushL(); // push onto cleanup stack for leave-safetymyRBuf.ReAllocL(newLength); // extend to newLengthCleanupStack::Pop();// remove from cleanup stackNote that the previous example uses the CleanupClosePushL()method of the RBuf class to push it onto the cleanup stack. As isusual for other R classes, cleanup is performed by calling Close() (orCleanupStack::PopAndDestroy() if the RBuf was pushed ontothe cleanup stack by a call to RBuf::CleanupClosePushL()).3.8.9 Literal DescriptorsLiteral descriptors are somewhat different from the other descriptor types.They are equivalent to static const char[] in C and because theyare constant, they can be built into ROM to save memory at runtime. Aset of macros, found in e32def.h, can be used to define Symbian OSliterals of two different types, _LIT and _L.The _LIT macro is preferred for Symbian OS literals, since it is moreefficient.

It is typically used as follows:50SYMBIAN OS DEVELOPMENT BASICS_LIT(KSymbianOS, "Symbian OS");The _LIT macro builds a named object (KSymbianOS) of typeTLitC16 into the program binary, storing the appropriate string (in thiscase, "Symbian OS"). The explicit macros _LIT8 and _LIT16 behavesimilarly, except that _LIT8 builds a narrow string of type TLitC8.TLitC8 and TLitC16 do not derive from TDesC8 or TDesC16, butthey have the same binary layouts as TBufC8 or TBufC16.

This allowsobjects of these types to be passed wherever TDesC is used.Symbian OS also defines literals to represent a blank string. There arethree variants of the null descriptor, defined as follows:// Build independent:_LIT(KNULLDesC,"");// 8-bit for narrow strings:_LIT8(KNULLDesC8,"");// 16-bit for Unicode strings:_LIT16(KNULLDesC16,"");Use of the _L macro is now deprecated in production code, though itmay still be used in test code (where memory use is less critical). It canbe defined and used in a single line of code, as follows:TBuf<10> KSymbianBuf(_L("Symbian OS"));3.8.10 Descriptor Class Types: SummaryThe previous subsections discussed the characteristics of each of thevarious descriptor types and classes. Table 3.2 summarizes them forreference.Figure 3.2 summarizes how the knowledge in Table 3.2 can be appliedwhen deciding what type of descriptor class to use.3.8.11 Using the Descriptor APIsLength() and Size()TDesC::Size() returns the size of the descriptor in bytes, whileTDesC::Length() returns the number of characters it contains.For 8-bit descriptors, the length and size of a descriptor are equivalentbecause the size of a character is a byte.

In native 16-bit strings, eachcharacter occupies two bytes. Thus Size() always returns a valuedouble that of Length() for neutral and explicitly wide descriptors.DESCRIPTORS – SYMBIAN OS STRINGS51Table 3.2 Descriptor Classes in SummaryNameModifiableApproximate CequivalentTypeNotesTDesCNon/aTDesYesn/aTPtrCNoTPtrYesconst char*(doesn’t own thedata)char* (doesn’town the data)NotinstantiableNotinstantiablePointerTBufCIndirectlyconst char []Stack bufferTBufYeschar []Stack bufferHBufCIndirectlyHeap bufferRBufYesTLitCNoconst char*(owns the data)char* (ownsthe data)Static constchar []Base class for all descriptors (exceptliterals)Base class for all modifiabledescriptorsThe data is stored separately from thedescriptor object, which is agnosticto its locationThe data is stored separately from thedescriptor object, which is agnosticto its locationThin template – size is fixed atcompile timeThin template – size is fixed atcompile timeUsed for dynamic data storage wheremodification is infrequentUsed for modifiable dynamic datastorageBuilt into ROMPointerHeap bufferLiteralMaxLength() and length modification methodsTDes::MaxLength() returns the maximum length of the modifiabledescriptor on which it is invoked.TDes::SetLength() can be used to adjust the descriptor length toany value between zero and its maximum length.TDes::Zero() sets the length of the descriptor object on which it isinvoked to zero.TPtr(C)::Set() and TDes::operator =()TPtr and TPtrC both provide Set() methods.

These can be used to setthe pointer to reference different string data. The length and maximumlength members of the descriptor object are updated accordingly.TDes provides an assignment operator to copy data into the memory already referenced by a modifiable descriptor. The length of thedescriptor is updated to that of the new contents, but the maximumlength is unchanged. So it is important that the length of new dataassigned to the descriptor is no longer than the maximum length, because52SYMBIAN OS DEVELOPMENT BASICSYESNOWill the descriptor bemodifiable?Has the memoryHas the memory forYESYESfor the descriptor datathe descriptor data beenTPtrTPtrCbeen allocated elsewhereallocated elsewhere(heap, stack or(heap or stack)?ROM)?TPtr can be used toTPtrC can reference datamodify previouslystored on the stack, heapallocated dataor in ROMNONOIs the size of thedescriptor known at compiletime and smaller than256 bytes?YESTBufIs the size of thedescriptor known at compiletime and smaller than256 bytes?NORBufNOHBufCYESTBufCIf binary data is contained in the descriptor,the classes ending in '8' (e.g.

TBuf8)should be used. If the data is explicitly .'wide', the classes ending in '16'(e.g. TBuf16) should be used. Otherwise,the neutral descriptor classes (which areimplicitly wide) should be used.Figure 3.2 Flow Chart to Guide the Choice of Descriptor Typeotherwise the copy will cause a panic. It is easy to confuse Set() withTDes::operator =().TBufC::Des() and HBufC::Des()TBufC and HBufC both provide a Des() method which returns amodifiable pointer descriptor to the data held in the buffer.

While thecontent of a non-modifiable buffer descriptor cannot be altered directly,calling Des() makes it possible to change the data. The method updatesthe length members of both the modifiable pointer descriptor and theDESCRIPTORS – SYMBIAN OS STRINGS53constant buffer descriptor it points to, if necessary. For example, forHBufC:HBufC* heapBuf = HBufC::NewLC(20);TPtr ptr(heapBuf->Des()); // Use ptr to modify heapBufA common inefficiency when using HBufC is to use Des() to returna modifiable pointer descriptor object (TPtr), when a non-modifiabledescriptor (TDesC) is required. It is not incorrect, but since HBufC itselfderives from TDesC, it can simply be de-referenced, which is clearer andmore efficient.const TDesC& CExample::Inefficient(){return (iHeapBuffer->Des());// could be replaced more efficiently withreturn (*iHeapBuffer);}Some of the other most commonly used APIs are:• TDesC::Find(), TDesC::Locate(), TDesC::Match().• Substring extraction using TDesC::Left(), TDesC::Right() andTDesC::Mid().• Adding data with the different variants of TDes::Append().• Data transfer between descriptors, by calling the various overloads ofTDes::Copy().You can find out more about each of the descriptor APIs in the SymbianDeveloper Library.3.8.12 Descriptors as Function Parameters and Return TypesAs Sections 3.8.2 and 3.8.3 described, the TDesC and TDes descriptorbase classes provide and implement the APIs for all descriptor operations.This means that the base classes can be used as function argumentsand return types, allowing descriptors to be passed around in codetransparently without forcing a dependency on a particular type.A function will simply declare whether a descriptor parameter shouldbe modifiable or non-modifiable, and whether it should be 8 or 16 bitsin width.

It doesn’t have to know the type of descriptor passed intoit. Unless a function takes or returns ownership, it doesn’t even need tospecify whether a descriptor is stack-based or heap-based. When definingfunctions, the abstract base classes should always be used as parameters54SYMBIAN OS DEVELOPMENT BASICSor return values. All descriptor parameters should be passed and returnedby reference, either as const TDesC& for constant descriptors or TDes&when modifiable. The only exception comes when transferring ownershipof a heap-based descriptor as a return value.

This should be specifiedexplicitly so that the caller can clean it up appropriately and avoid amemory leak.// Read only parameter (16 bit)void SomeFunctionL(const TDesC& aReadOnlyDescriptor);// Read only return value (8 bit)const TDesC8& SomeFunction();// Read/Write parameter (16 bit)void SomeFunctionL(TDes& aReadWriteDescriptor);// Return ownership of HBufC*HBufC* SomeFunctionL();For additional information about descriptors, you should consult theSymbian Developer Library or one of the Symbian Press books, listed atthe end of Chapter 6.3.9 Arrays on Symbian OSSymbian OS does not include an implementation of the collections foundin the Standard Template Library.

Instead, it offers various templatizedclasses for static and dynamic arrays. This section will help you make itclearer which array class does what and how.The most basic class is TFixedArray, which is a static array class,to be used when you know at build time how many data items the arraywill contain.3.9.1 Static ArraysTFixedArray wraps a standard fixed-length C++ [] array to addrange checking, and prevent out-of-bounds access by panicking toflag the programming error. The range-checking assertions are calledin debug builds only, or in both debug and release builds if yourequire it, by calling different methods on the class to access theelements. The class also provides some additional functions to navigate to the beginning and end, return the number of elements in thearray, and clean up the elements it contains.

Further information canbe found in the Symbian Developer Library that accompanies eachSDK.ARRAYS ON SYMBIAN OS553.9.2 Dynamic ArraysOn Symbian OS, the implementation of a dynamic array may either use:• A single heap cell as a ‘flat’ buffer to hold the array elements, which isresized as necessary. This memory layout is preferred when the speedof element lookup is an important factor or if the array is not expectedto be frequently resized.• A number of segments, using a doubly linked list to manage them.This layout is best for large arrays which are expected to be resizedfrequently, or when elements are regularly inserted into or deleted,since repeated reallocations in a single flat buffer may result in heapthrashing as elements are shuffled around.The original dynamic array classes provided in early versions ofSymbian OS were C classes, of which there are a number of differenttypes, all of which have names prefixed by "CArray".

We refer to themhere generically as "CArrayX" classes. The different types of array existto store various types of array element:• Fixed elements – all items have the same fixed size (e.g., TInt,TRect).• Variable elements – the items may have different size, so they arepointers to objects of variable lengths contained elsewhere on theheap (e.g., HBufC* or TAny*).• Pointer elements – the items are the pointers to CBase-derivedobjects.• Packaged elements – the items are ‘packed’ T-class objects of variablelength; that is, each element is preceded by its length.Table 3.3 summarizes the combinations defined in the SDK.As Symbian OS evolved, a second set of dynamic array classes(RArray and RPointerArray) was added later (the CArrayX classeswere retained).

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

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

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

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