Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 92

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 92 страницаB. Stroustrup - The C++ Programming Language (794319) страница 922019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In particular, it is hard to know where in a program they are used, and they can be a source of data races inmulti-threaded programs (§41.2.4), leading to very obscure bugs.Placing variables in a namespace helps a bit, but such variables are still subject to data races.If you must use global variables, at least restrict their use to a single source file. This restrictioncan be achieved in one of two ways:[1] Place declarations in an unnamed namespace.[2] Declare an entity static.An unnamed namespace (§14.4.8) can be used to make names local to a compilation unit.

Theeffect of an unnamed namespace is very similar to that of internal linkage. For example:// file 1.cpp:namespace {class X { /* ... */ };void f();int i;// ...}// file2.cpp:class X { /* ... */ };void f();int i;// ...The function f() in file1.cpp is not the same function as the f() in file2.cpp. Having a name local to atranslation unit and also using that same name elsewhere for an entity with external linkage is asking for trouble.The keyword static (confusingly) means ‘‘use internal linkage’’ (§44.2.3).

That’s an unfortunate leftover from the earliest days of C.424Source Files and ProgramsChapter 1515.2.2 Header FilesThe types in all declarations of the same object, function, class, etc., must be consistent. Consequently, the source code submitted to the compiler and later linked together must be consistent.One imperfect but simple method of achieving consistency for declarations in different translationunits is to #include header files containing interface information in source files containingexecutable code and/or data definitions.The #include mechanism is a text manipulation facility for gathering source program fragmentstogether into a single unit (file) for compilation. Consider:#include "to_be_included"The#include-directive replaces the line in which the #include appears with the contents of the fileto_be_included.

The content of to_be_included should be C++ source text because the compiler willproceed to read it.To include standard-library headers, use the angle brackets, < and >, around the name instead ofquotes. For example:#include <iostream>#include "myheader.h"// from standard include directory// from current directoryUnfortunately, spaces are significant within the < > or " " of an include directive:#include < iostream >// will not find <iostream>It seems extravagant to recompile a source file each time it is included somewhere, but the text canbe a reasonably dense encoding for program interface information, and the compiler need only analyze details actually used (e.g., template bodies are often not completely analyzed until instantiationtime; §26.3).

Furthermore, most modern C++ implementations provide some form of (implicit orexplicit) precompiling of header files to minimize the work needed to handle repeated compilationof the same header.As a rule of thumb, a header may contain:Named namespacesinline namespacesType definitionsTemplate declarationsTemplate definitionsFunction declarationsinline function definitionsconstexpr function definitionsData declarationsconst definitionsconstexpr definitionsEnumerationsName declarationsType aliasesnamespace N { /∗ ... ∗/ }inline namespace N { /∗ ... ∗/ }struct Point { int x, y; };template<class T> class Z;template<class T> class V { /∗ ...

∗/ };extern int strlen(const char∗);inline char get(char∗ p) { /∗ ... ∗/ }constexpr int fac(int n) { return (n<2) ? 1 : fac(n−1); }extern int a;const float pi = 3.141593;constexpr float pi2 = pi∗pi;enum class Light { red, yellow, green };class Matrix;using value_type = long;Section 15.2.2Header FilesCompile-time assertionsInclude directivesMacro definitionsConditional compilation directivesComments425static_assert(4<=sizeof(int),"small ints");#include<algorithm>#define VERSION 12.03#ifdef __cplusplus/∗ check for end of file ∗/This rule of thumb for what may be placed in a header is not a language requirement. It is simply areasonable way of using the #include mechanism to express the physical structure of a program.Conversely, a header should never contain:Ordinary function definitionsData definitionsAggregate definitionsUnnamed namespacesusing-directiveschar get(char∗ p) {return ∗p++; }int a;short tbl[] = { 1, 2, 3 };namespace { /∗ ...

∗/ }using namespace Foo;Including a header containing such definitions will lead to errors or (in the case of the using-directive) to confusion. Header files are conventionally suffixed by .h, and files containing function ordata definitions are suffixed by .cpp. They are therefore often referred to as ‘‘.h files’’ and ‘‘.cppfiles,’’ respectively. Other conventions, such as .c, .C, .cxx, .cc, .hh, and hpp are also found. Themanual for your compiler will be quite specific about this issue.The reason for recommending that the definition of simple constants, but not the definition ofaggregates, be placed in header files is that it is hard for implementations to avoid replication ofaggregates presented in several translation units.

Furthermore, the simple cases are far more common and therefore more important for generating good code.It is wise not to be too clever about the use of #include. My recommendations are:• #include only as headers (don’t #include ‘‘ordinary source code containing variable definitions and non-inline functions’’).• #include only complete declarations and definitions.• #include only in the global scope, in linkage specification blocks, and in namespace definitions when converting old code (§15.2.4).• Place all #includes before other code to minimize unintended dependencies.• Avoid macro magic.• Minimize the use of names (especially aliases) not local to a header in a header.One of my least favorite activities is tracking down an error caused by a name being macro-substituted into something completely different by a macro defined in an indirectly #included header thatI have never even heard of.15.2.3 The One-Definition RuleA given class, enumeration, and template, etc., must be defined exactly once in a program.From a practical point of view, this means that there must be exactly one definition of, say, aclass residing in a single file somewhere.

Unfortunately, the language rule cannot be that simple.For example, the definition of a class may be composed through macro expansion (ugh!), and a definition of a class may be textually included in two source files by #include directives (§15.2.2).426Source Files and ProgramsChapter 15Worse, a ‘‘file’’ isn’t a concept that is part of the C++ language definition; there exist implementations that do not store programs in source files.Consequently, the rule in the standard that says that there must be a unique definition of a class,template, etc., is phrased in a somewhat more complicated and subtle manner. This rule is commonly referred to as the one-definition rule (‘‘the ODR’’). That is, two definitions of a class, template, or inline function are accepted as examples of the same unique definition if and only if[1] they appear in different translation units, and[2] they are token-for-token identical, and[3] the meanings of those tokens are the same in both translation units.For example:// file1.cpp:struct S { int a; char b; };void f(S∗);// file2.cpp:struct S { int a; char b; };void f(S∗ p) { /* ...

*/ }The ODR says that this example is valid and that S refers to the same class in both source files.However, it is unwise to write out a definition twice like that. Someone maintaining file2.cpp willnaturally assume that the definition of S in file2.cpp is the only definition of S and so feel free tochange it. This could introduce a hard-to-detect error.The intent of the ODR is to allow inclusion of a class definition in different translation unitsfrom a common source file.

For example:// s.h:struct S { int a; char b; };void f(S∗);// file1.cpp:#include "s.h"// use f() here// file2.cpp:#include "s.h"void f(S∗ p) { /* ... */ }or graphically:s.h:file1.cpp:struct S { int a; char b; };void f(S∗);#include "s.h"// use f() herefile2.cpp:#include "s.h"void f(S∗ p) { /∗ ... ∗/ }Section 15.2.3The One-Definition Rule427Here are examples of the three ways of violating the ODR:// file1.cpp:struct S1 { int a; char b; };struct S1 { int a; char b; };// error : double definitionThis is an error because a struct may not be defined twice in a single translation unit.// file1.cpp:struct S2 { int a; char b; };// file2.cpp:struct S2 { int a; char bb; };// errorThis is an error because S2 is used to name classes that differ in a member name.// file1.cpp:typedef int X;struct S3 { X a; char b; };// file2.cpp:typedef char X;struct S3 { X a; char b; }; // errorHere the two definitions of S3 are token-for-token identical, but the example is an error because themeaning of the name X has sneakily been made to differ in the two files.Checking against inconsistent class definitions in separate translation units is beyond the abilityof most C++ implementations.

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

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

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

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