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

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

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

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

your class. If you add or remove a virtual functionin the base class, you will change the vtable position of any virtualfunctions defined by a derived class. Any code that was compiled againstthe original version of the derived class will now be using an incorrectvtable layout.This rule also applies to any base classes from which the class derivesand the order from which they are derived if the class uses multipleinheritance. Changes to either will affect the layout of the vtable.Likewise, you must not modify a virtual function if this means changingthe parameters, the return type or the use of const.

However, you canmake changes to the internal operation of the function, for example a bugfix, as long as the documented behavior of the function is not changed.PREVENTING COMPATIBILITY BREAKS285Do Not Re-Order Virtual FunctionsAlthough not stated in the C++ standard, the order in which virtualmember functions are specified in the class definition can be assumed tobe the only factor which affects the order in which they appear in thevirtual function table. You should not change this order, since client codecompiled against an earlier version of the virtual function table will callwhat has become a completely different virtual function.Do Not Override a Virtual Function that was Previously InheritedIf you override a virtual function which was previously inherited, you arealtering the virtual function table of the class. However, existing clientcode is compiled against the original vtable and will thus continue toaccess the inherited base-class function rather than the new, overridden,version.

This leads to inconsistency between callers compiled against theoriginal version of the library and those compiled against the new version.Although it does not strictly result in incompatibility, this is best avoided.For example, a client of CSiamese version 1.0 calling SleepL()invokes CCat::SleepL(), while clients of version 2.0 invokeCSiamese::SleepL():class CCat :{public:IMPORT_Cpublic:IMPORT_CIMPORT_Cprotected:CCat();};public CBase // Abstract base classvirtual ∼CCat() =0;virtual void PlayL(); // Default implementationvirtual void SleepL(); // Default implementationclass CSiamese : public CCat// Version 1.0{public:IMPORT_C virtual ∼CSiamese();public:// Overrides PlayL() but defaults to CCat::SleepL()IMPORT_C virtual void PlayL();// ...};class CSiamese : public CCat// Version 2.0{public:IMPORT_C virtual ∼CSiamese();public:// Now overrides PlayL() and SleepL()IMPORT_C virtual void PlayL();IMPORT_C virtual void SleepL();// ...};286COMPATIBILITYDo Not Modify the Documented Semantics of an APIIf you change the documented behavior of a class or global function, orthe meaning of a constant, you may break compatibility with previouslypublished versions used by client code, regardless of whether source andbinary compatibility are maintained.

As a very simple example, you maysupply a class which, when supplied with a data set, returns the averagevalue of that data. If the first release of the Average() function returnsthe arithmetic mean value, the second release of Average() should notbe changed to return the median value, or some other interpretation ofan average. As always, of course, if all the callers of the function canaccept the change, or if the effect is limited to the internals of your owncomponents, then such a modification is acceptable.Do Not Remove constThe semantics of ”const” should not be removed, since this will bea source-incompatible change.

This means that you should not removethe const-ness of a parameter, return type or class method that wereoriginally specified as const.Do Not Change from Pass by Value to Pass by Reference, or Vice versaIf parameters or return values were originally passed by value, you willbreak binary compatibility if you change them to reference values (or viceversa). When a parameter is passed by value to a function, the compilergenerates a stack copy of the entire parameter and passes it to the function.However, if the function signature is changed to accept the parameter byreference, a word-sized reference to the original object is passed to thefunction instead. The stack frame for a pass-by-reference function call isthus significantly different from that for a pass-by-value function call.

Inaddition, the semantics of passing by value and by reference are verydifferent – as discussed in Chapter 20 – which inevitably causes binaryincompatibility.class TColor{...private:TInt iRed;TInt iGreen;TInt iBlue;};// version 1.0// Pass in TColor by value (12 bytes)IMPORT_C void Fill(TColor aBackground);// version 2.0 – binary compatibility is brokenWHAT CAN I CHANGE WITHOUT BREAKING BINARY COMPATIBILITY?287// Pass in TColor by reference (4 bytes)IMPORT_C void Fill(TColor& aBackground);18.5 What Can I Change Without Breaking BinaryCompatibility?You Can Extend an APIYou can add classes, constants, global data or functions without breakingcompatibility.3 Likewise, a class can be extended by the addition of staticmember functions or non-virtual member functions. Recall the definitionof the direction of compatibility at the beginning of this chapter – anyextension of an API is, by its very nature, not forward-compatible.If you add functions that are exported for external code to use (asdescribed in Chapter 20), you must add the new exports to the bottomof the module definition file (.def) used to determine the ordinalnumber by which the linker identifies the exported function.

You mustavoid reordering the list of exported functions. This will break binarycompatibility, as described above.As I discussed earlier, you should not add virtual member functionsto classes which may have been subclassed (i.e., externally derivableclasses), since this causes the vtable of the deriving classes to bere-ordered.You Can Modify the Private Internals of a ClassChanges to private class methods that are not exported and are not virtualdo not break client compatibility. Likewise for protected methods in aclass which is not derivable.

However, the functions must not be calledby externally-accessible inline methods, since the call inside the inlinemethod would be compiled into external calling code – and would bebroken by an incompatible change to the internals of the class. As I discussin Chapter 21, it is general good practice to restrict, or eliminate, the useof publicly-accessible inline functions, particularly where compatibilityis an issue. This is also discussed further in Section 18.6.Changes to private class member data are also permissible, unless itresults in a change to the size of the class object or moves the positionof public or protected data in the class object (exposed directly, throughinheritance or through public inline ”accessor” methods).You Can Relax Access SpecificationThe C++ access specifier (public, protected, private) doesn’t affectthe layout of a class and can be relaxed without affecting the data order3You should endeavor to avoid any name clashes within the component or others inthe global namespace – otherwise the change will be source-incompatible.288COMPATIBILITYof the object.

The position of member data in a class object is determinedsolely by the position of the data as it is specified in the class definition.It is not sensible to change the access specification to a more restrictedform, e.g. from public to private, because, although it does not affectthe code, it means that the member data becomes invisible to externalclients when previously it was visible.

A future change to the componentmight incorrectly assume that the data has always been private andmodify its purpose, affecting external components dependent upon it. Inaddition, any existing client which accesses that data will no longer beable to do so – a source-incompatible change.You Can Substitute Pointers for References and Vice VersaChanging from a pointer to a reference parameter or return type (or viceversa) in a class method does not break binary compatibility. This isbecause references and pointers can be considered to be represented inthe same way by the C++ compiler.You Can Change the Names of Exported Non-Virtual FunctionsSymbian OS is linked purely by ordinal and not by name and signature.This means that it is possible to make changes to the name of exportedfunctions and retain binary, if not source, compatibility.You Can Widen the InputInput can be made more generic (”widened”) as long as input thatis currently valid retains the same interpretation.

Thus, for example, afunction can be modified to accept a less derived pointer4 or extra valuescan be added to an enumeration, as long as it is extended rather thanre-ordered, which would change the original values.You Can Narrow the OutputOutput can be made less generic (”narrowed”) as long as any currentoutput values are preserved. For example, the return pointer of a functioncan be made more derived as long as the new return type applies to theoriginal return value.5 For multiple inheritance, say, a pointer to a classis unchanged when it is converted to a pointer to the first base class in4Say class CSiamese derives from class CCat.

If the pointer passed to a function wasoriginally of type CSiamese, it is acceptable to change the function signature to take apointer to the less-derived CCat type.5Using the same example of class CSiamese which derives from CCat, if the pointerreturned from a function was originally of type CCat, it is acceptable to change the functionsignature to return a pointer to the more-derived CSiamese type.BEST PRACTICE: PLANNING FOR FUTURE CHANGES289the inheritance declaration order. That is, the layout of the object followsthe inheritance order specified.You Can Apply the const SpecifierIt is acceptable to change non-const parameters, return types or the”this” pointer to be const in a non-virtual function, as long as theparameter is no more complicated than a reference or pointer (i.e., not areference to a pointer or a pointer to a pointer).

This is because you canpass non-const parameters to const functions or those that take constparameters. In effect, this is an extension of the ”widen input” guidelinedescribed above.18.6 Best Practice: Planning for Future ChangesDon’t Inline FunctionsAs described earlier, and later in Chapter 21 which discusses good codingpractice, an inline function is compiled into the client’s code. This meansthat a client must recompile its code in order to pick up a change to aninline function.If you want to use private inline methods within the class, you shouldensure that they are not accessible externally, say by implementing themin a file that is accessible only to the code module in question.Using an inline function increases the coupling between your component and its dependents, which should generally be avoided.Don’t Expose Any Public or Protected Member DataThe position of data is fixed for the lifetime of the object if it is externallyaccessible, either directly or through derivation.

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

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

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

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