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

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

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

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

To form a pointer to (oraccess the value of) a direct nonstatic member of an object obj, the construction of obj shall have startedand its destruction shall not have completed, otherwise the computation of the pointer value (or accessingthe member value) results in undefined behavior. [Example:structstructstructstructstructABCDX{:::{};virtual A { };B { };virtual A { D(A*); };X(A*); };struct E : C, D, X {E() : D(this),X(this)// undefined: upcast from E* to A*// might use path E* → D* → A*// but D is not constructed// D((C*)this), // defined:// E* → C* defined because E() has started// and C* → A* defined because// C fully constructed// defined: upon construction of X,// C/B/D/A sublattice is fully constructed{ }};—end example]3Member functions, including virtual functions (10.3), can be called during construction or destruction(12.6.2).

When a virtual function is called directly or indirectly from a constructor (including from themem-initializer for a data member) or from a destructor, and the object to which the call applies is theobject under construction or destruction, the function called is the one defined in the constructor ordestructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object(1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expressionrefers to the object under construction or destruction but its type is neither the constructor or destructor’sown class or one of its bases, the result of the call is undefined.

[Example:class V {public:virtual void f();virtual void g();};201ISO/IEC 14882:1998(E)© ISO/IEC12.7 Construction and destruction12 Special member functionsclass A : public virtual V {public:virtual void f();};class B : public virtual V {public:virtual void g();B(V*, A*);};class D : public A, B {public:virtual void f();virtual void g();D() : B((A*)this, this) { }};B::B(V* v, A* a) {f();g();v->g();a->f();}// calls V::f, not A::f// calls B::g, not D::g// v is base of B, the call is well-defined, calls B::g// undefined behavior, a’s type not a base of B—end example]4The typeid operator (5.2.8) can be used during construction or destruction (12.6.2).

When typeid isused in a constructor (including from the mem-initializer for a data member) or in a destructor, or used in afunction called (directly or indirectly) from a constructor or destructor, if the operand of typeid refers tothe object under construction or destruction, typeid yields the type_info representing the constructoror destructor’s class. If the operand of typeid refers to the object under construction or destruction andthe static type of the operand is neither the constructor or destructor’s class nor one of its bases, the result oftypeid is undefined.5Dynamic_casts (5.2.7) can be used during construction or destruction (12.6.2). When adynamic_cast is used in a constructor (including from the mem-initializer for a data member) or in adestructor, or used in a function called (directly or indirectly) from a constructor or destructor, if theoperand of the dynamic_cast refers to the object under construction or destruction, this object is considered to be a most derived object that has the type of the constructor or destructor’s class.

If the operand ofthe dynamic_cast refers to the object under construction or destruction and the static type of theoperand is not a pointer to or object of the constructor or destructor’s own class or one of its bases, thedynamic_cast results in undefined behavior.6[Example:class V {public:virtual void f();};class A : public virtual V { };class B : public virtual V {public:B(V*, A*);};202© ISO/IECISO/IEC 14882:1998(E)12 Special member functions12.7 Construction and destructionclass D : public A, B {public:D() : B((A*)this, this) { }};B::B(V* v, A* a) {typeid(*this);typeid(*v);typeid(*a);dynamic_cast<B*>(v);dynamic_cast<B*>(a);// type_info for B// well-defined: *v has type V, a base of B// yields type_info for B// undefined behavior: type A not a base of B// well-defined: v of type V*, V base of B// results in B*// undefined behavior,// a has type A*, A not a base of B}—end example]12.8 Copying class objects[class.copy]1A class object can be copied in two ways, by initialization (12.1, 8.5), including for function argumentpassing (5.2.2) and for function value return (6.6.3), and by assignment (5.17).

Conceptually, these twooperations are implemented by a copy constructor (12.1) and copy assignment operator (13.5.3).2A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&,volatile X& or const volatile X&, and either there are no other parameters or else all otherparameters have default arguments (8.3.6).106) [Example: X::X(const X&) and X::X(X&, int=1)are copy constructors.class X {// ...public:X(int);X(const X&, int = 1);};X a(1);X b(a, 0);X c = b;// calls X(int);// calls X(const X&, int);// calls X(const X&, int);—end example] [Note: all forms of copy constructor may be declared for a class.

[Example:class X {// ...public:X(const X&);X(X&);};// OK—end example] —end note] [Note: if a class X only has a copy constructor with a parameter of type X&,an initializer of type const X or volatile X cannot initialize an object of type (possibily cv-qualified)X. [Example:__________________106) Because a template constructor is never a copy constructor, the presence of such a template does not suppress the implicit declaration of a copy constructor.

Template constructors participate in overload resolution with other constructors, including copy constructors, and a template constructor may be used to copy an object if it provides a better match than other constructors.203ISO/IEC 14882:1998(E)© ISO/IEC12.8 Copying class objects12 Special member functionsstruct X {X();X(X&);};const X cx;X x = cx;// default constructor// copy constructor with a nonconst parameter// error – X::X(X&) cannot copy cx into x—end example] —end note]3A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cvqualified) X and either there are no other parameters or else all other parameters have default arguments.

Amember function template is never instantiated to perform the copy of a class object to an object of its classtype. [Example:struct S {template<typename T> S(T);};S f();void g() {S a( f() ); // does not instantiate member template}—end example]4If the class definition does not explicitly declare a copy constructor, one is declared implicitly. Thus, forthe class definitionstruct X {X(const X&, int);};a copy constructor is implicitly-declared. If the user-declared constructor is later defined asX::X(const X& x, int i =0) { /* ...

*/ }then any use of X’s copy constructor is ill-formed because of the ambiguity; no diagnostic is required.5The implicitly-declared copy constructor for a class X will have the formX::X(const X&)if— each direct or virtual base class B of X has a copy constructor whose first parameter is of type constB& or const volatile B&, and— for all the nonstatic data members of X that are of a class type M (or array thereof), each such class typehas a copy constructor whose first parameter is of type const M& or const volatile M&.107)Otherwise, the implicitly declared copy constructor will have the formX::X(X&)An implicitly-declared copy constructor is an inline public member of its class.6A copy constructor for class X is trivial if it is implicitly declared and if— class X has no virtual functions (10.3) and no virtual base classes (10.1), and— each direct base class of X has a trivial copy constructor, and— for all the nonstatic data members of X that are of class type (or array thereof), each such class type has__________________107) This implies that the reference parameter of the implicitly-declared copy constructor cannot bind to a volatile lvalue; seeC.1.8.204© ISO/IECISO/IEC 14882:1998(E)12 Special member functions12.8 Copying class objectsa trivial copy constructor;otherwise the copy constructor is non-trivial.7An implicitly-declared copy constructor is implicitly defined if it is used to initialize an object of its classtype from a copy of an object of its class type or of a class type derived from its class type108).

[Note: thecopy constructor is implicitly defined even if the implementation elided its use (12.2). ] A program is illformed if the class for which a copy constructor is implicitly defined has:— a nonstatic data member of class type (or array thereof) with an inaccessible or ambiguous copy constructor, or— a base class with an inaccessible or ambiguous copy constructor.Before the implicitly-declared copy constructor for a class is implicitly defined, all implicitly-declared copyconstructors for its direct and virtual base classes and its nonstatic data members shall have been implicitlydefined. [Note: an implicitly-declared copy constructor has an exception-specification (15.4).

]8The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. Theorder of copying is the same as the order of initialization of bases and members in a user-defined constructor (see 12.6.2). Each subobject is copied in the manner appropriate to its type:— if the subobject is of class type, the copy constructor for the class is used;— if the subobject is an array, each element is copied, in the manner appropriate to the element type;— if the subobject is of scalar type, the built-in assignment operator is used.Virtual base class subobjects shall be copied only once by the implicitly-defined copy constructor (see12.6.2).9A user-declared copy assignment operator X::operator= is a non-static non-template member functionof class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatileX&.109) [Note: an overloaded assignment operator must be declared to have only one parameter; see 13.5.3.] [Note: more than one form of copy assignment operator may be declared for a class.

] [Note: if a class Xonly has a copy assignment operator with a parameter of type X&, an expression of type const X cannot beassigned to an object of type X. [Example:struct X {X();X& operator=(X&);};const X cx;X x;void f() {x = cx;// error:// X::operator=(X&) cannot assign cx into x}—end example] —end note]10If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly.The implicitly-declared copy assignment operator for a class X will have the formX& X::operator=(const X&)if__________________108) See 8.5 for more details on direct and copy initialization.109) Because a template assignment operator is never a copy assignment operator, the presence of such a template does not suppressthe implicit declaration of a copy assignment operator.

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

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

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

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