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

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

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

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

Figure 5.2 compares the memory layoutsof TBuf and TBufC.TBufC <12>iLength12iBufHello World!TDesCTBufCTBufC <15>iLength12iMaxLength15TDesCTDesiBufHello World!TBufFigure 5.2 Buffer descriptorsThese descriptors are useful for fixed-size or relatively small strings,say up to the length of a 256-character filename. Being stack-based, theyshould be used when they have a lifetime that coincides with that of theircreator.

They may be considered equivalent to char[] in C, but withthe benefit of overflow checking.64DESCRIPTORS: SYMBIAN OS STRINGSTBufC<n>This is the non-modifiable buffer class, used to hold constant string orbinary data. The class derives from TBufCBase (which derives fromTDesC, and exists as an inheritance convenience rather than to be useddirectly). TBufC<n> is a thin template class which uses an integer valueto determine the size of the data area allocated for the buffer descriptorobject. Chapter 19 describes the thin template pattern and its role inSymbian OS code.The class defines several constructors that allow non-modifiable buffersto be constructed from a copy of any other descriptor or from a zeroterminated string.

They can also be created empty and filled later since,although the data is non-modifiable, the entire contents of the buffermay be replaced by calling the assignment operator defined by the class.The replacement data may be another non-modifiable descriptor or azero-terminated string, but in each case the new data length must notexceed the length specified in the template parameter when the bufferwas created._LIT(KPalindrome, "Satan, oscillate my metallic sonatas");TBufC<50> buf1(KPalindrome); // Constructed from literal descriptorTBufC<50> buf2(buf1);// Constructed from buf1// Constructed from a NULL-terminated C stringTBufC<30> buf3((TText*)"Never odd or even");TBufC<50> buf4;// Constructed empty, length = 0// Copy and replacebuf4 = buf1; // buf4 contains data copied from buf1, length modifiedbuf1 = buf3; // buf1 contains data copied from buf3, length modifiedbuf3 = buf2; // Panic! Max length of buf3 is insufficient for buf2 dataThe class also defines a Des() method which returns a modifiablepointer descriptor for the data represented by the buffer.

So, whilethe content of a non-modifiable buffer descriptor cannot normally bealtered directly, other than by complete replacement of the data, it ispossible to change the data indirectly by creating a modifiable pointerdescriptor into the buffer. When the data is modified through the pointerdescriptor, the lengths of both the pointer descriptor and the constantbuffer descriptor are changed although, of course, the length is notautomatically extended because the descriptor classes do not providememory management._LIT8(KPalindrome, "Satan, oscillate my metallic sonatas");TBufC8<40> buf(KPalindrome); // Constructed from literal descriptorTPtr8 ptr(buf.Des()); // data is the string in buf, max length = 40// Illustrates the use of ptr to copy and replace contents of bufptr = (TText8*)"Do Geese see God?";HEAP-BASED BUFFER DESCRIPTORS65ASSERT(ptr.Length()==buf.Length());_LIT8(KPalindrome2, "Are we not drawn onward, we few, drawn onward tonew era?");ptr = KPalindrome2; // Panic! KPalindrome2 exceeds max length of ptr(=40)TBuf<n>Like the corresponding non-modifiable buffer class, this class for nonconstant buffer data is a thin template class, the integer value determiningthe maximum allowed length of the buffer.

It derives from TBufBase,which itself derives from TDes, thus inheriting the full range of descriptor operations in TDes and TDesC. TBuf<n> defines a number ofconstructors and assignment operators, similar to those offered by itsnon-modifiable counterpart.As with all descriptors, its memory management is your responsibilityand, although the buffer is modifiable, it cannot be extended beyond theinitial maximum length set on construction. If the contents of the bufferneed to expand, it’s up to you to make sure that you either make theoriginal allocation large enough at compile time or dynamically allocatethe descriptor at runtime.

The only way you can do the latter is to usea heap descriptor, described below. If this responsibility is too onerousand you want the resizing done for you, I suggest you consider usinga dynamic buffer, as described in Chapter 7, bearing in mind that theassociated overhead will be higher._LIT(KPalindrome, "Satan, oscillate my metallic sonatas");TBuf<40> buf1(KPalindrome); // Constructed from literal descriptorTBuf<40> buf2(buf1);// Constructed from constant buffer descriptorTBuf8<40> buf3((TText8*)"Do Geese see God?"); // from C stringTBuf<40> buf4; // Constructed empty, length = 0, maximum length = 40// Illustrate copy and replacebuf4 = buf2; // buf2 copied into buf4, updating length and max lengthbuf3 = (TText8*)"Murder for a jar of red rum"; // updated from C stringThe stack-based buffer descriptors, TBuf<n> and TBufC<n>, areuseful for fixed-size or relatively small strings, say up to the lengthof a 256-character filename.5.5 Heap-Based Buffer DescriptorsHeap-based descriptors can be used for string data that isn’t in ROM andis not placed on the stack because it is too big.

Heap-based descriptors66DESCRIPTORS: SYMBIAN OS STRINGScan be used where they may have a longer lifetime than their creator,for example, passed to an asynchronous function. They are also usefulwhere the length of a buffer to be created is not known at compile timeand are used where malloc’d data would be used in C.The class representing these descriptors is HBufC (explicitly HBufC8or HBufC16) although these descriptors are always referred to by pointer,HBufC*. You’ll notice that, by starting with ”H”, the class doesn’tcomply with the naming conventions described in Chapter 1. The class isexceptional and doesn’t really fit any of the standard Symbian OS typesexactly. Thus, it is simply prefixed with H to indicate that the data isstored on the heap.

If you’re interested in how the cleanup stack handlesHBufC, see Chapter 3.The HBufC class exports a number of static NewL() functions tocreate the buffer on the heap. These follow the two-phase constructionmodel (described in Chapter 4) since they may leave if there is insufficientmemory available. There are no public constructors and all heap buffersmust be constructed using one of these methods (or from one of theAlloc() or AllocL() methods of the TDesC class which you may useto spawn an HBufC copy of any descriptor).As you’ll note from the ”C” in the class name, these descriptors are nonmodifiable, although, in common with the stack-based non-modifiablebuffer descriptors, the class provides a set of assignment operators toallow the entire contents of the buffer to be replaced. As with TBufC, thelength of the replacing data must not exceed the length of the heap cellallocated for the buffer or a panic occurs.In common with TBufC, the heap-based descriptors can be manipulated at runtime by creating a modifiable pointer descriptor, TPtr, usingthe Des() method._LIT(KPalindrome, "Do Geese see God?");TBufC<20> stackBuf(KPalindrome);// Allocates an empty heap descriptor of max length 20HBufC* heapBuf = HBufC::NewLC(20);TInt length = heapBuf->Length();// Current length = 0TPtr ptr(heapBuf->Des());// Modification of the heap descriptorptr = stackBuf; // Copies stackBuf contents into heapBuflength = heapBuf->Length();// length = 17HBufC* heapBuf2 = stackBuf.AllocLC(); // From stack bufferlength = heapBuf2->Length();// length = 17_LIT(KPalindrome2, "Palindrome");*heapBuf2 = KPalindrome2;// Copy and replace data in heapBuf2length = heapBuf2->Length(); // length = 10CleanupStack::PopAndDestroy(2, heapBuf);Remember, the heap descriptors can be created dynamically to thesize you require, but they are not automatically resized should you wantHEAP-BASED BUFFER DESCRIPTORS67to grow the buffer.

You must ensure that the buffer has sufficient memoryavailable for the modification operation you intend to use.To help you with this, the HBufC class also defines a set of ReAllocL() methods to allow you to extend the heap buffer, which maypotentially move the buffer from its previous location in memory (andmay of course leave if there is insufficient memory). If the HBufC* isstored on the cleanup stack, moving the pointer as a result of memoryreallocation can cause significant problems either in the event of a leaveor if the cleanup stack’s PopAndDestroy() function is used to destroythe memory. If you call Des() on a heap descriptor to acquire a TPtr,the iPtr member of this object is not guaranteed to be valid after reallocation; it’s safest to assume that the buffer will have moved and createa new TPtr accordingly.There is no modifiable heap descriptor, HBuf, which you may haveexpected in order to make heap buffers symmetrical with TBuf stackbuffers.

The reasons for this are manifold. First, the expectation mightreasonably be that the maximum length of a modifiable HBuf class wouldexpand and contract on the heap as the content was modified. The goal ofdescriptors is efficiency, with memory managed by the programmer notthe descriptor object, but an HBuf class which is modifiable but does notdynamically resize may be considered somewhat odd. To add dynamicresizing to HBuf would be difficult and costly in terms of code sizebecause, as I’ve described, all the modifiable descriptor operations areimplemented in its base class, TDes.

In addition, if dynamic reallocationwere added to HBuf, the programmer would have to be made awarethat the location of the buffer might change as code is reallocated, andthat certain functions might fail if there is insufficient memory, probablyrequiring a new set of leaving functions to be added to the class.Heap buffers were initially intended to allow efficient reading ofconstant resource strings of variable length. Being non-modifiable, theysave on the additional four bytes required to store a maximum length,which allows them to be as compact as possible. The Des() methodpermits them to be modified if necessary, when the programmer makesan explicit choice to do so.

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

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

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

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