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

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

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

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

Any dependent binaries that built against version 1.0 and do not need to berecompiled will continue to work. It is only when the client code comesto be rebuilt against version 2.0 that it will be affected by source incompatibility (it must be modified to replace the CInstrument class withthe new CStringInstrument class).On Symbian OS, a typical source-incompatible change involves modifying the internals of a member function to give it the potential to leavewhen previously it could not do so.

To adhere strictly to the naming convention, the name of the function must also be modified by the additionof a suffix L.If you change your component and dependent components can recompile against the new version without the need to make any changes, itcan be said to be source-compatible. An example of a source-compatiblechange is a bug fix to the internals of an exported function, which doesn’trequire a change to the function definition itself.18.3Binary CompatibilityBinary compatibility is achieved when one component, dependent onanother, can continue to run without recompilation or re-linking after thecomponent on which it depends is modified. The compatibility extendsacross compilation and link boundaries.One example of a binary-compatible change is the addition to a classof a public, non-virtual function which is exported from the library withan ordinal1 that comes after the previous set of exported functions.

A1As I described in Chapter 13, Symbian OS uses dynamic linking by ordinal, ratherthan function name matching, to reduce the size overhead of its export tables. However,PREVENTING COMPATIBILITY BREAKS281client component which was dependent on the original version of thelibrary is not affected by the addition of a function to the end of the exportlist of the library.

Thus the change can be said to be binary-compatibleand backward-compatible (as well as source-compatible).However, if the addition of a new function to the class causesthe ordinals of the exported functions to be reordered, the change isnot binary-compatible, although it continues to be source-compatible.Dependent code must be recompiled, because otherwise it would usethe original, now invalid, ordinal numbers to identify the exports.Of course, when we discuss the need for compatibility, this is withrelation to the API which has been published to external components.You may make as many internally-incompatible changes to your codeas you need to, since it is only your components that are affected.

Therestrictions I’ll discuss in the rest of this chapter apply to changes whichaffect published, public APIs.Let’s move on to consider some of the practical aspects of code, tohelp you understand the kind of source code changes that can affectcompatibility. I’ll list some guidelines about which code changes do anddo not affect the binary layout at a class or DLL level. These derive froman understanding of the way a compiler interprets the C++ standard.

Itis only by deriving a set of rules in this way that we can be confidentas to which changes can be safely applied without breaking dependentcode.Many of the following guidelines are based on whether class methodsor member data are ”visible” to dependent code. This assumes thatcalling code gains visibility through legitimate means, that is, throughexported header files, using standard object-oriented C++ to access andmanipulate the methods and data encapsulated in C++ objects.18.4 Preventing Compatibility BreaksDo Not Change the Size of a Class ObjectYou should not change the size of a class object (e.g. by adding orremoving data) unless you can guarantee that:• your class is not externally derivable• the only code that allocates an object resides within your component,or it has a non-public constructor that prevents it from being createdon the stackthis has significant implications for binary compatibility, because the ordinals of exportedfunctions must not be changed between one release of a DLL and another (otherwise codewhich originally used the old DLL will not be able to locate the functions it needs in thenew version of the DLL).282COMPATIBILITY• the class has a virtual destructor.The reasons for this rule are fairly straightforward.

First, the size ofmemory required for an object to be allocated on the stack is determinedfor each component at build time, and to change the size of an objectwould affect previously compiled client code, unless the client is guaranteed to instantiate the object only on the heap, say by using a NewL()factory function.Additionally, access to data members within an object occurs throughan offset from the this pointer.

If the class size is changed, say by addinga data member, the offsets of the data members of derived classes arerendered invalid.To ensure that an object of a class cannot be derived or instantiated except by members (or friends) of the class, it should have private,non-inline and non-exported constructors. It is not sufficient simply notto declare any constructors for the class, since the compiler will thengenerate an implicit, public default constructor. On Symbian OS, all Cclasses derive from CBase, which defines a protected default constructor, and prevents the compiler from generating an implicit version.2 Ifyour class needs a default constructor, you should simply define it asprivate and implement it in source, or at least, not inline where it ispublicly accessible.Here’s a definition for a typical, non-derivable class:Class CNonDerivable : public CBase{public:// Factory - instantiates the object via ConstructL()IMPORT_C static CNonDerivable* NewL();// Virtual destructor, inherited from CBaseIMPORT_C virtual ∼CNonDerivable();public:...

// Omitted for clarity – public exports & virtual functionsprivate:// constructor is private, not protected, to prevent subclassingCNonDerivable();void ConstructL();private:... // Omitted for clarity – private member data goes here};So, to recap, unless you can guarantee that all objects have beenconstructed within your component on the heap, and are not derivable,2Class CBase also declares, but does not define, a private copy constructor (andcorresponding assignment operator) to prevent the compiler generating the implicit versionsthat perform potentially unsafe shallow copies of member data.

Neither the copy constructornor assignment operator are implemented, in order to prevent copy operations of CBaseclasses – although of course you can implement your own, public, versions for derivedclasses where this is valid.PREVENTING COMPATIBILITY BREAKS283you should not change the size of the member data of a class. If youfollow these rules, you must also take into account that the objectmay be destroyed by an external component, which must deallocate allthe memory it occupies. To guarantee that the object and the memoryallocated for it are destroyed correctly, the class must have a virtualdestructor. Again, you’ll inherit a virtual destructor from CBase whenimplementing a C class.You are unlikely to have a valid reason for preventing a stack-basedT class from being instantiated on the stack, so you should never modifythe size of an externally visible T class.Do Not Remove Anything AccessibleIf you remove something from an API which is used by an externalcomponent, that component’s code will no longer compile against theAPI (a break in source compatibility) nor run against its implementation(a break in binary compatibility).Thus, at an API level, you should not remove any externally-visibleclass, function, enumeration (or any value within an enumeration) orglobal data, such as string literals or constants.At a class level, you should not remove any methods or class memberdata.

Even private member data should not be removed, in general,because the size of the resulting object will change, which should beavoided for reasons described above.Do Not Rearrange Accessible Class Member DataIf you don’t remove class member data but merely rearrange it, youcan still cause problems to client code that accesses that data directlybecause, as I described above, the offset of the member data from theobject’s this pointer will be changed.You must not change the position of member data in a class if thatdata is:• public (or protected, if the client can derive from the class)• exposed through public or protected inline methods (which will havebeen compiled into client code).This rule also means that you cannot change the order of the baseclasses from which a class multiply inherits without breaking compatibility, because this order affects the overall data layout of the derived object.Do Not Rearrange the Ordinal of Exported FunctionsIn Chapter 13, I briefly mentioned the mechanism by which the API ofa component is accessible to an external component, via a numerically284COMPATIBILITYordered list of exported functions which are ”frozen” into a moduledefinition (.def) file.

Each exported function is associated with anordinal number, which is used by the linker to identify the function.If you later re-order the .def file, say by adding a new export withinthe list of current exports, the ordinal number values will change andpreviously compiled code will be unable to locate the correct function.For example, say component A exports a method DoSomethingL() atordinal 9, which is used by component B. Component A is later extendedto export a new function, which is simply added to the start of the ordinallist, at ordinal 1.

This changes the ordinal value of DoSomethingL()to 10. Unless component B is re-linked, it will still expect to be able tocall DoSomethingL() at ordinal 9 but instead will call a completelydifferent function. The change breaks binary compatibility. To avoid this,the new export should be added to the end of the .def file, which assignsit a new, previously unused, ordinal value.The use of a .def file means that exported functions within aC++ class definition may be reordered safely, say to group themalphabetically or logically, as long as the underlying order of thoseexports in the .def file is not affected.Do Not Add, Remove or Modify the Virtual Functionsof Externally Derivable ClassesIf a class is externally derivable (i.e. if it has an exported or inlined,public or protected constructor) you must not alter the nature of thevirtual functions in any way, because this will break compatibility withcalling code.The reason why virtual functions should not be added to or removedfrom a derivable class is as follows: if the class is externally derivableand a derived class defines its own virtual functions, these will be placedin the virtual function table (vtable) directly after those defined bythe base class, i.e.

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

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

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

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