Главная » Просмотр файлов » Стандарт C++ 98

Стандарт C++ 98 (1119566), страница 80

Файл №1119566 Стандарт C++ 98 (Стандарт C++ 98) 80 страницаСтандарт C++ 98 (1119566) страница 802019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The automatic objects are destroyed in the reverse order of thecompletion of their construction.2An object that is partially constructed or partially destroyed will have destructors executed for all of itsfully constructed subobjects, that is, for subobjects for which the constructor has completed execution andthe destructor has not yet begun execution. Should a constructor for an element of an automatic arraythrow an exception, only the constructed elements of that array will be destroyed.

If the object or array wasallocated in a new-expression and the new-expression does not contain a new-placement, the deallocationfunction (3.7.3.2, 12.5) is called to free the storage occupied by the object; the deallocation function is chosen as specified in 5.3.4. If the object or array was allocated in a new-expression and the new-expressioncontains a new-placement, the storage occupied by the object is deallocated only if an appropriate placement operator delete is found, as specified in 5.3.4.3The process of calling destructors for automatic objects constructed on the path from a try block to athrow-expression is called “stack unwinding.” [Note: If a destructor called during stack unwinding exitswith an exception, terminate is called (15.5.1).

So destructors should generally catch exceptions andnot let them propagate out of the destructor. —end note]15.3 Handling an exception[except.handle]1The exception-declaration in a handler describes the type(s) of exceptions that can cause that handler to beentered. The exception-declaration shall not denote an incomplete type. The exception-declaration shallnot denote a pointer or reference to an incomplete type, other than void*, const void*, volatilevoid*, or const volatile void*.

Types shall not be defined in an exception-declaration.2A handler of type “array of T” or “function returning T” is adjusted to be of type “pointer to T” or “pointerto function returning T”, respectively.3A handler is a match for a throw-expression with an object of type E if— The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cvqualifiers), or— the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or— the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handlerby either or both of— a standard pointer conversion (4.10) not involving conversions to pointers to private or protected orambiguous classes— a qualification conversion[Note: a throw-expression which is an integral constant expression of integer type that evaluates to zerodoes not match a handler of pointer type; that is, the null pointer constant conversions (4.10, 4.11) do notapply.

]4[Example:classclassclassclassMatherr { /* ... */ virtual vf(); };Overflow: public Matherr { /* ... */ };Underflow: public Matherr { /* ... */ };Zerodivide: public Matherr { /* ... */ };void f(){try {g();}294© ISO/IECISO/IEC 14882:1998(E)15 Exception handling15.3 Handling an exceptioncatch (Overflow oo) {// ...}catch (Matherr mm) {// ...}}Here, the Overflow handler will catch exceptions of type Overflow and the Matherr handler willcatch exceptions of type Matherr and of all types publicly derived from Matherr including exceptionsof type Underflow and Zerodivide. ]5The handlers for a try block are tried in order of appearance. That makes it possible to write handlers thatcan never be executed, for example by placing a handler for a derived class after a handler for a corresponding base class.6A ... in a handler’s exception-declaration functions similarly to ...

in a function parameter declaration; it specifies a match for any exception. If present, a ... handler shall be the last handler for its tryblock.7If no match is found among the handlers for a try block, the search for a matching handler continues in adynamically surrounding try block.8An exception is considered handled upon entry to a handler. [Note: the stack will have been unwound atthat point. ]9If no matching handler is found in a program, the function terminate() is called; whether or not thestack is unwound before this call to terminate() is implementation-defined (15.5.1).10Referring to any non-static member or base class of an object in the handler for a function-try-block of aconstructor or destructor for that object results in undefined behavior.11The fully constructed base classes and members of an object shall be destroyed before entering the handlerof a function-try-block of a constructor or destructor for that object.12The scope and lifetime of the parameters of a function or constructor extend into the handlers of afunction-try-block.13Exceptions thrown in destructors of objects with static storage duration or in constructors of namespacescope objects are not caught by a function-try-block on main().14If the handlers of a function-try-block contain a jump into the body of a constructor or destructor, the program is ill-formed.15If a return statement appears in a handler of the function-try-block of a constructor, the program is illformed.16The exception being handled is rethrown if control reaches the end of a handler of the function-try-block ofa constructor or destructor.

Otherwise, a function returns when control reaches the end of a handler for thefunction-try-block (6.6.3). Flowing off the end of a function-try-block is equivalent to a return with novalue; this results in undefined behavior in a value-returning function (6.6.3).17When the exception-declaration specifies a class type, a copy constructor is used to initialize either theobject declared in the exception-declaration or, if the exception-declaration does not specify a name, a temporary object of that type.

The object shall not have an abstract class type. The object is destroyed whenthe handler exits, after the destruction of any automatic objects initialized within the handler. The copyconstructor and destructor shall be accessible in the context of the handler. If the copy constructor anddestructor are implicitly declared (12.8), such a use in the handler causes these functions to be implicitlydefined; otherwise, the program shall provide a definition for these functions.295ISO/IEC 14882:1998(E)© ISO/IEC15.3 Handling an exception15 Exception handling18If the use of a temporary object can be eliminated without changing the meaning of the program except forexecution of constructors and destructors associated with the use of the temporary object, then the optionalname can be bound directly to the temporary object specified in a throw-expression causing the handler tobe executed. The copy constructor and destructor associated with the object shall be accessible even whenthe temporary object is eliminated.19When the handler declares a non-constant object, any changes to that object will not affect the temporaryobject that was initialized by execution of the throw-expression.

When the handler declares a reference to anon-constant object, any changes to the referenced object are changes to the temporary object initializedwhen the throw-expression was executed and will have effect should that object be rethrown.15.4 Exception specifications1[except.spec]A function declaration lists exceptions that its function might directly or indirectly throw by using anexception-specification as a suffix of its declarator.exception-specification:throw ( type-id-listopt )type-id-list:type-idtype-id-list , type-idAn exception-specification shall appear only on a function declarator in a function, pointer, reference orpointer to member declaration or definition.

An exception-specification shall not appear in a typedef declaration. [Example:void f() throw(int);void (*fp)() throw (int);void g(void pfa() throw(int));typedef int (*pf)() throw(int);// OK// OK// OK// ill-formed—end example] A type denoted in an exception-specification shall not denote an incomplete type.

A typedenoted in an exception-specification shall not denote a pointer or reference to an incomplete type, otherthan void*, const void*, volatile void*, or const volatile void*.2If any declaration of a function has an exception-specification, all declarations, including the definition andan explicit specialization, of that function shall have an exception-specification with the same set of typeids. If any declaration of a pointer to function, reference to function, or pointer to member function has anexception-specification, all occurrences of that declaration shall have an exception-specification with thesame set of type-ids. In an explicit instantiation directive an exception-specification may be specified, butis not required.

If an exception-specification is specified in an explicit instantiation directive, it shall havethe same set of type-ids as other declarations of that function. A diagnostic is required only if the sets oftype-ids are different within a single translation unit.3If a virtual function has an exception-specification, all declarations, including the definition, of any functionthat overrides that virtual function in any derived class shall only allow exceptions that are allowed by theexception-specification of the base class virtual function.

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

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

Список файлов учебной работы

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