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

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

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

However,there is one exception, which is that you should always use void whena function or method has no return type, instead of TAny.The following example defines an 8-bit signed integer x and assignsthe value 123:TInt8 x = 123;The following example defines a 64-bit signed integer y and assigns avalue to it:TInt64 y = MAKE_TINT64(0x1234567, 0x89ABCDEF);The following example defines two 32-bit unsigned integers, a and b,and assigns them with the low word and high word of y respectively:TUint32 a = I64LOW(y);TUint32 b = I64HIGH(y);30SYMBIAN OS DEVELOPMENT BASICSTable 3.1 Fundamental Data Types on Symbian OSData typesDescriptionC++ built-in typesTIntSigned integer.

It is guaranteed to be atleast 32 bits in all implementationsUnsigned integer. It is guaranteed to be atleast 32 bits in all implementations32-bit, 16-bit and 8-bit signed integersigned intTUintTInt32, TInt16,TInt8TUint32, TUint16,TUint832-bit, 16-bit and 8-bit unsigned integerTText8, TText1664-bit integer64-bit unsigned integerBuild-independent text character.

It ismapped to TText168-bit and16-bit unsigned characterTReal32TReal, TReal64TBoolTAny32-bit floating point number64-bit floating point numberBoolean typePointer typeTInt64TUint64TTextunsigned intlong int, short int,signed charunsigned long int,unsigned short int,unsigned charlong longunsigned long longunsigned short intunsigned short int,unsigned charfloatdoubleintvoid3.2 Symbian OS Class ConventionsBy convention, there are several class types on Symbian OS, each ofwhich has different characteristics, such as where objects may be created(on the heap, on the stack, or on either) and how those objects shouldlater be cleaned up. The classes are named with a prefix according totype, and this convention makes the creation, use and destruction ofobjects more straightforward.

When writing code, the required behaviorof a class should be matched to the Symbian OS class characteristics.Later, a user of an unfamiliar class can be confident in how to instantiatean object, use it and then destroy it without leaking memory.3.2.1 T ClassesClass names prefixed with T are used for classes that behave like thefundamental built-in data types (it is for this reason that they are prefixedwith the same letter as the typedefs described above – the ‘T’ is for‘Type’).Just like the built-in types, T classes do not have an explicit destructor.In consequence, T classes must not contain any member data whichitself has a destructor.

T classes contain all their data internally and haveSYMBIAN OS CLASS CONVENTIONS31no pointers, references or handles to data, unless that data is owned byanother object responsible for its cleanup.T-class objects are usually stack-based but they can also be createdon the heap – indeed, some T classes should only ever be heap-basedbecause the resulting object would otherwise occupy too much stackspace.

A good rule of thumb is that any object larger than 512 bytesshould always be heap-based rather than created on the stack, since stackspace is limited for applications running on Symbian OS. One way toprevent the object from being instantiated on the stack is to rename theclass, and make it a C class, since C-class objects are always created onthe heap, as the next subsection describes.Tip: T classes can be created on the heap as well as on the stack.3.2.2 C ClassesC-class objects must always be created on the heap. Unlike T classes, Cclasses may contain and own pointers.For Symbian OS memory management to work correctly, every C classmust ultimately derive from class CBase (defined in the Symbian OSheader file e32base.h).

This class has three characteristics, which areinherited by every C class:• Safe destruction. CBase has a virtual destructor, so a CBase-derivedobject is destroyed properly by deletion through a base-class pointer.• Zero initialization. CBase overloads operator new to zero-initializean object when it is first allocated on the heap. This means that allmember data in a CBase-derived object will be zero-filled when itis first created, so this does not need to be done explicitly in theconstructor.• CBase also declares a private copy constructor and assignmentoperator. Their declaration prevents calling code from accidentallyperforming invalid copy operations on C classes.On instantiation, the member data contained within a C class typicallyneeds to perform operations that may fail.

A good example is instantiationof an object that performs a memory allocation, which fails if there isinsufficient memory available. This kind of failure is called a leave onSymbian OS, and is discussed in more detail shortly. A constructor shouldnever be able to leave, because this can cause memory leaks, as we willdiscuss in Section 3.6 on two-phase construction. To avoid the potentialfor memory leaks upon construction, C classes are characterized by an32SYMBIAN OS DEVELOPMENT BASICSidiom called two-phase construction, which also prevents accidentalcreation of objects of a C class on the stack.C classes will be discussed more when we deal with two-phaseconstruction and the cleanup stack.3.2.3 R ClassesR classes own an external resource handle, for example a handle to aserver session.

R classes are diverse, and vary from holding a file serversession handle (e.g., class RFs) to memory allocated on the heap (e.g.,class RBuf). R classes are often small, and usually contain no othermember data besides the resource handle. R-class objects may exist asclass members, as local stack-based variables or, occasionally, on theheap.Initializing R classes usually requires calling a special method, suchas Open(), Create() or Connect(). Similarly, destroying R classesusually involves calling a special cleanup method, which is usuallynamed Close() although it may sometimes be named something else,such as Reset().

It is rare for an R class to have a destructor too – itgenerally does not need one because cleanup is performed in the cleanupmethod.Although you will probably use a number of Symbian R classes, thereare only a few cases where you may need to write your own R class, forexample when you are creating a client-server application.3.2.4 M ClassesOn Symbian OS, M classes are often used in callback or observer classes.An M class is an abstract interface class which declares pure virtualfunctions and has no member data.

A concrete class deriving from sucha class typically inherits from CBase (or a CBase-derived class) as itsfirst base class and from one or more M-class ‘mixin’ interfaces, andimplements the interface functions.An M class should usually have only pure virtual functions, but mayoccasionally have non-pure virtual functions.Tip: The only form of multiple inheritance encouraged on SymbianC++ is that which uses one CBase-derived class and mixes in one ormore M classes.

The correct class-derivation order is always to put theCBase-derived class first, to emphasize the primary inheritance treeand ensure proper cleanup through the cleanup stack.LEAVES AND EXCEPTION HANDLING333.2.5 Static ClassesSome Symbian OS utility classes, such as User, Math and Mem, take noprefix letter and contain only static member functions. The classes themselves cannot be instantiated; their functions must instead be called usingthe scope-resolution operator – for example, User::After() whichsuspends the currently running thread for the number of microsecondsspecified as a parameter of the function.

A static class is sometimesimplemented to act as a factory class.3.3 Leaves and Exception HandlingLeaves can be thought of as the equivalent of exception handling onSymbian OS. Think of them as using just one exception class, and simplyincluding an integer (known as a ‘leave code’) inside the exception toidentify its cause.Tip: Symbian OS v9 also supports C++ standard exceptions. Thismakes it easier to port existing C++ code to Symbian OS. However,even if your code only uses standard C++ exceptions, leaves are afundamental part of Symbian error handling and are used throughoutthe system, so it pays to understand them thoroughly.How do you know whether a function may leave? This is where wesee another Symbian C++ naming convention, which is to terminate thename with a trailing ‘L’.

In fact, of all Symbian OS naming conventions,this one is probably the most important rule: if a leaving function isnot named correctly, callers of that function cannot know about it andmay leak memory in the event a leave occurs. We’ll see how this couldhappen shortly.Tip: It is standard practice when defining leaving functions to avoidreturning an error code as well. That is, since leaving functionsalready highlight a failure (through the leave code), they should notalso return error values. Any error that occurs in a leaving functionshould be passed out as a leave; if the function does not leaveit is deemed to have succeeded and will return normally. Exceptunder exception circumstances, leaving functions should return voidunless they return a pointer or reference to a resource that they haveallocated.34SYMBIAN OS DEVELOPMENT BASICSSince it is not part of the C++ standard, the trailing L cannot be checkedduring compilation, and can sometimes be forgotten.

Symbian OS provides a helpful tool, LeaveScan, to check code for incorrectly namedleaving functions. Some other static code-analysis tools are discussed inChapter 6.3.3.1 The Difference between Panics and LeavesBefore any further discussion of leaves, it is important to make thedistinction between leaves (which are Symbian exceptions) and panics.Leaves are used to propagate errors to where they can be handled.A leave does not terminate the flow of execution on Symbian OS. Incontrast, panics are used to stop code running. They are intended toensure robust code logic by flagging up programming errors in a way thatcannot be ignored.

Unlike a leave, a panic cannot be trapped, because itterminates the thread in which it occurs.On phone hardware, a panic is seen as an ‘Application closed’ messagebox. When debugging on the emulator builds, the panic breaks the codeinto the debugger by default, so you can look at the call stack anddiagnose the problem.To cause a panic in the current thread, the Panic() method of thestatic User class can be used. It is not possible to panic other threads inthe system, except those running in the same process. To panic anotherthread in the running process, your code should open an RThreadhandle and call RThread::Panic().

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

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

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

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