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

Стандарт C++ 11 (1119564), страница 60

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

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

[ Example:void f() {int i;extern void g(int x = i);// ...}//error— end example ]8The keyword this shall not be used in a default argument of a member function. [ Example:class A {void f(A* p = this) { }};// error— end example ]9Default arguments are evaluated each time the function is called. The order of evaluation of functionarguments is unspecified. Consequently, parameters of a function shall not be used in a default argument,even if they are not evaluated.

Parameters of a function declared before a default argument are in scopeand can hide namespace and class member names. [ Example:int a;int f(int a, int b = a);// error: parameter a// used as default argumenttypedef int I;int g(float I, int b = I(2));int h(int a, int b = sizeof(a));// error: parameter I found// error, parameter a used// in default argument— end example ] Similarly, a non-static member shall not be used in a default argument, even if it is notevaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it isused to form a pointer to member (5.3.1). [ Example: the declaration of X::mem1() in the following exampleis ill-formed because no object is supplied for the non-static member X::a used as an initializer.int b;class X {int a;int mem1(int i = a);// error: non-static member a§ 8.3.6© ISO/IEC 2011 – All rights reserved197ISO/IEC 14882:2011(E)int mem2(int i = b);static int b;};// used as default argument// OK; use X::bThe declaration of X::mem2() is meaningful, however, since no object is needed to access the static memberX::b.

Classes, objects, and members are described in Clause 9. — end example ] A default argument is notpart of the type of a function. [ Example:int f(int = 0);void h() {int j = f(1);int k = f();}int (*p1)(int) = &f;int (*p2)() = &f;// OK, means f(0)// error: type mismatch— end example ] When a declaration of a function is introduced by way of a using-declaration (7.3.3), anydefault argument information associated with the declaration is made known as well. If the function isredeclared thereafter in the namespace with additional default arguments, the additional arguments are alsoknown at any point following the redeclaration where the using-declaration is in scope.10A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determinedby the static type of the pointer or reference denoting the object.

An overriding function in a derived classdoes not acquire default arguments from the function it overrides. [ Example:struct A {virtual void f(int a = 7);};struct B : public A {void f(int a);};void m() {B* pb = new B;A* pa = pb;pa->f();// OK, calls pa->B::f(7)pb->f();// error: wrong number of arguments for B::f()}— end example ]8.4Function definitions8.4.11In general[dcl.fct.def ][dcl.fct.def.general]Function definitions have the formfunction-definition:attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt function-bodyfunction-body:ctor-initializeropt compound-statementfunction-try-block= default ;= delete ;§ 8.4.1198© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)Any informal reference to the body of a function should be interpreted as a reference to the non-terminalfunction-body.

The optional attribute-specifier-seq in a function-definition appertains to the function. Avirt-specifier-seq can be part of a function-definition only if it is a member-declaration (9.2).2The declarator in a function-definition shall have the formD1 ( parameter-declaration-clause ) cv-qualifier-seqoptref-qualifieropt exception-specificationopt attribute-specifier-seqopt trailing-return-typeoptas described in 8.3.5.

A function shall be defined only in namespace or class scope.3[ Example: a simple example of a complete function definition isint max(int a, int b, int c) {int m = (a > b) ? a : b;return (m > c) ? m : c;}Here int is the decl-specifier-seq; max(int a, int b, int c) is the declarator; { /* ...function-body. — end example ]*/ } is the4A ctor-initializer is used only in a constructor; see 12.1 and 12.6.5A cv-qualifier-seq or a ref-qualifier (or both) can be part of a non-static member function declaration,non-static member function definition, or pointer to member function only (8.3.5); see 9.3.2.6[ Note: Unused parameters need not be named.

For example,void print(int a, int) {std::printf("a = %d\n",a);}— end note ]7In the function-body, a function-local predefined variable denotes a block-scope object of static storage duration that is implicitly defined (see 3.3.3).8The function-local predefined variable __func__ is defined as if a definition of the formstatic const char __func__[] = "function-name ";had been provided, where function-name is an implementation-defined string.

It is unspecified whether sucha variable has an address distinct from that of any other object in the program.102[ Example:struct S {S() : s(__func__) { }const char *s;};void f(const char * s = __func__);// OK// error: __func__ is undeclared— end example ]8.4.21Explicitly-defaulted functions[dcl.fct.def.default]A function definition of the form:102) Implementations are permitted to provide additional predefined variables with names that are reserved to the implementation (17.6.4.3.2). If a predefined variable is not odr-used (3.2), its string value need not be present in the program image.§ 8.4.2© ISO/IEC 2011 – All rights reserved199ISO/IEC 14882:2011(E)attribute-specifier-seqopt decl-specifier-seqopt declarator = default ;is called an explicitly-defaulted definition.

A function that is explicitly defaulted shall— be a special member function,— have the same declared function type (except for possibly differing ref-qualifiers and except that inthe case of a copy constructor or copy assignment operator, the parameter type may be “reference tonon-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,and— not have default arguments.2An explicitly-defaulted function may be declared constexpr only if it would have been implicitly declared asconstexpr, and may have an explicit exception-specification only if it is compatible (15.4) with the exceptionspecification on the implicit declaration.

If a function is explicitly defaulted on its first declaration,— it is implicitly considered to be constexpr if the implicit declaration would be,— it is implicitly considered to have the same exception-specification as if it had been implicitly declared (15.4), and— in the case of a copy constructor, move constructor, copy assignment operator, or move assignmentoperator, it shall have the same parameter type as if it had been implicitly declared.3[ Example:struct S {constexpr S() = default;S(int a = 0) = default;void operator=(const S&) = default;~S() throw(int) = default;private:int i;S(S&);};S::S(S&) = default;////////ill-formed:ill-formed:ill-formed:ill-formed:implicit S() is not constexprdefault argumentnon-matching return typeexception specification does not match// OK: private copy constructor// OK: defines copy constructor— end example ]4Explicitly-defaulted functions and implicitly-declared functions are collectively called defaulted functions,and the implementation shall provide implicit definitions for them (12.1 12.4, 12.8), which might meandefining them as deleted.

A special member function is user-provided if it is user-declared and not explicitlydefaulted or deleted on its first declaration. A user-provided explicitly-defaulted function (i.e., explicitlydefaulted after its first declaration) is defined at the point where it is explicitly defaulted; if such a functionis implicitly defined as deleted, the program is ill-formed.

[ Note: Declaring a function as defaulted after itsfirst declaration can provide efficient execution and concise definition while enabling a stable binary interfaceto an evolving code base. — end note ]5[ Example:struct trivial {trivial() = default;trivial(const trivial&) = default;trivial(trivial&&) = default;trivial& operator=(const trivial&) = default;trivial& operator=(trivial&&) = default;~trivial() = default;};§ 8.4.2200© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)struct nontrivial1 {nontrivial1();};nontrivial1::nontrivial1() = default;// not first declaration— end example ]8.4.31Deleted definitions[dcl.fct.def.delete]A function definition of the form:attribute-specifier-seqopt decl-specifier-seqopt declarator = delete ;is called a deleted definition. A function with a deleted definition is also called a deleted function.2A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.[ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-memberto the function.

It applies even for references in expressions that are not potentially-evaluated. If a functionis overloaded, it is referenced only if the function is selected by overload resolution. — end note ]3[ Example: One can enforce non-default initialization and non-integral initialization withstruct sometype {sometype() = delete;// OK, but redundantsome_type(std::intmax_t) = delete;some_type(double);};— end example ][ Example: One can prevent use of a class in certain new expressions by using deleted definitions of a userdeclared operator new for that class.struct sometype {void *operator new(std::size_t) = delete;void *operator new[](std::size_t) = delete;};sometype *p = new sometype;// error, deleted class operator newsometype *q = new sometype[3]; // error, deleted class operator new[]— end example ][ Example: One can make a class uncopyable, i.e.

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

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

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

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