Читаем C++ Primer Plus полностью

The noexcept keyword is used to indicate that a function doesn’t throw an exception. It also can be used as an operator that determines whether its operand (an expression) potentially could throw an exception. It returns false if the operand could throw an exception and true otherwise. For example, consider the following declarations:

int hilt(int);

int halt(int) noexcept;

The expression noexcept(hilt) would evaluate as false, as the declaration of hilt() doesn’t guarantee that an exception won’t be thrown. But noexcept(halt) will evaluate as true.

F. The string Template Class

Much of this appendix is a bit technical. However, if you just want to know the capabilities of the string template class, you can concentrate on the descriptions of the various string methods.

The string class is based on a template definition:

template,

                 class Allocator = allocator >

class basic_string {...};

Here charT represents the type stored in the string. The traits parameter represents a class that defines necessary properties that a type must possess to be represented as a string. For example, it should have a length() method that returns the length of a string, represented as an array of type charT. The end of such an array is indicated by the value charT(0), the generalization of the null character. (The expression charT(0) is a type cast of 0 to type charT. It could be just 0, as it is for type char, or more generally, it could be an object created by a charT constructor.) The class also includes methods for comparing values, and so on. The Allocator parameter represents a class to handle memory allocation for the string. The default allocator template uses new and delete in the standard ways.

There are four predefined specializations:

typedef basic_string string;

typedef basic_string u16string;

typedef basic_string u32string;

typedef basic_string wstring;

These specializations, in turn, use the following specializations:

char_traits

allocator

char_traits

allocator

char_traits

allocator

char_traits

allocator

You can create a string class for some type other than char or wchar_t by defining a traits class and using the basic_string template.

Thirteen Types and a Constant

The basic_string template defines several types that are used later in defining the methods:

typedef traits                                traits_type;

typedef typename traits::char_type            value_type;

typedef Allocator                             allocator_type;

typedef typename Allocator::size_type         size_type;

typedef typename Allocator::difference_type   difference_type;

typedef typename Allocator::reference         reference;

typedef typename Allocator::const_reference   const_reference;

typedef typename Allocator::pointer           pointer;

typedef typename Allocator::const_pointer     const_pointer;

Note that traits is a template parameter that corresponds to some specific type, such as char_traits; traits_type becomes a typedef for that specific type. The following notation means that char_type is a type name defined in the class represented by traits:

typedef typename traits::char_type          value_type;

The keyword typename is used to tell the compiler that the expression traits::char_type is a type. For the string specialization, for example, value_type is char.

size_type is used like size_of, except that it returns the size of a string in terms of the stored type. For the string specialization, that would be in terms of char, in which case size_type is the same as size_of. It is an unsigned type.

difference_type is used to measure the distance between two elements of a string, again in units corresponding to the size of a single element. Typically, it would be a signed version of the type underlying size_type.

For the char specialization, pointer is type char *, and reference is type char &. However, if you create a specialization for a type of your own design, these types (pointer and reference) could refer to classes that have the same properties as the more basic pointers and references.

To allow Standard Template Library (STL) algorithms to be used with strings, the template defines some iterator types:

typedef (models random access iterator)         iterator;

typedef (models random access iterator)         const_iterator;

typedef std::reverse_iterator         reverse_iterator;

typedef std::reverse_iterator   const_reverse_iterator;

The template defines a static constant:

static const size_type npos = -1;

Because size_type is unsigned, assigning the value -1 actually amounts to assigning the largest possible unsigned value to npos. This value corresponds to one greater than the largest possible array index.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных