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

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

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

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

Good design and theabsence of errors cannot be guaranteed merely by the presence or absence of specific language features. However, the language features and the type system are provided for the programmer to precisely and concisely represent a design in code.The notion of static types and compile-time type checking is central to effective use of C++.The use of static types is key to expressiveness, maintainability, and performance. Following Simula, the design of user-defined types with interfaces that are checked at compile time is key to theexpressiveness of C++. The C++ type system is extensible in nontrivial ways (Chapter 3, Chapter16, Chapter 18, Chapter 19, Chapter 21, Chapter 23, Chapter 28, Chapter 29), aiming for equal support for built-in types and user-defined types.C++ type-checking and data-hiding features rely on compile-time analysis of programs to prevent accidental corruption of data.

They do not provide secrecy or protection against someone whois deliberately breaking the rules: C++ protects against accident, not against fraud. They can, however, be used freely without incurring run-time or space overheads. The idea is that to be useful, alanguage feature must not only be elegant, it must also be affordable in the context of a real-worldprogram.C++’s static type system is flexible, and the use of simple user-defined types implies little, ifany overhead. The aim is to support a style of programming that represents distinct ideas as distinct types, rather than just using generalizations, such as integer, floating-point number, string,‘‘raw memory,’’ and ‘‘object,’’ everywhere.

A type-rich style of programming makes code more14Notes to the ReaderChapter 1readable, maintainable, and analyzable. A trivial type system allows only trivial analysis, whereasa type-rich style of programming opens opportunities for nontrivial error detection and optimization. C++ compilers and development tools support such type-based analysis [Stroustrup,2012].Maintaining most of C as a subset and preserving the direct mapping to hardware needed for themost demanding low-level systems programming tasks implies the ability to break the static typesystem. However, my ideal is (and always was) complete type safety. In this, I agree with DennisRitchie, who said, ‘‘C is a strongly typed, weakly checked language.’’ Note that Simula was bothtype-safe and flexible. In fact, my ideal when I started on C++ was ‘‘Algol68 with Classes’’ ratherthan ‘‘C with Classes.’’ However, the list of solid reasons against basing my work on type-safeAlgol68 [Woodward,1974] was long and painful.

So, perfect type safety is an ideal that C++ as alanguage can only approximate. But it is an ideal that C++ programmers (especially librarybuilders) can strive for. Over the years, the set of language features, standard-library components,and techniques supporting that ideal has grown. Outside of low-level sections of code (hopefullyisolated by type-safe interfaces), code that interfaces to code obeying different language conventions (e.g., an operating system call interface), and the implementations of fundamental abstractions(e.g., string and vector), there is now little need for type-unsafe code.1.2.3 C CompatibilityC++ was developed from the C programming language and, with few exceptions, retains C as asubset. The main reasons for relying on C were to build on a proven set of low-level languagefacilities and to be part of a technical community.

Great importance was attached to retaining ahigh degree of compatibility with C [Koenig,1989] [Stroustrup,1994] (Chapter 44); this (unfortunately) precluded cleaning up the C syntax. The continuing, more or less parallel evolution of Cand C++ has been a constant source of concern and requires constant attention [Stroustrup,2002].Having two committees devoted to keeping two widely used languages ‘‘as compatible as possible’’is not a particularly good way of organizing work. In particular, there are differences in opinion asto the value of compatibility, differences in opinion on what constitutes good programming, anddifferences in opinion on what support is needed for good programming.

Just keeping up communication between the committees is a large amount of work.One hundred percent C/C++ compatibility was never a goal for C++ because that would compromise type safety and the smooth integration of user-defined and built-in types. However, thedefinition of C++ has been repeatedly reviewed to remove gratuitous incompatibilities; C++ is nowmore compatible with C than it was originally.

C++98 adopted many details from C89 (§44.3.1).When C then evolved from C89 [C,1990] to C99 [C,1999], C++ adopted almost all of the new features, leaving out VLAs (variable-length arrays) as a misfeature and designated initializers asredundant. C’s facilities for low-level systems programming tasks are retained and enhanced; forexample, see inlining (§3.2.1.1, §12.1.5, §16.2.8) and constexpr (§2.2.3, §10.4, §12.1.6).Conversely, modern C has adopted (with varying degrees of faithfulness and effectiveness)many features from C++ (e.g., const, function prototypes, and inlining; see [Stroustrup,2002]).The definition of C++ has been revised to ensure that a construct that is both legal C and legalC++ has the same meaning in both languages (§44.3).One of the original aims for C was to replace assembly coding for the most demanding systemsprogramming tasks.

When C++ was designed, care was taken not to compromise the gains in thisSection 1.2.3C Compatibility15area. The difference between C and C++ is primarily in the degree of emphasis on types and structure. C is expressive and permissive. Through extensive use of the type system, C++ is even moreexpressive without loss of performance.Knowing C is not a prerequisite for learning C++. Programming in C encourages many techniques and tricks that are rendered unnecessary by C++ language features. For example, explicittype conversion (casting) is less frequently needed in C++ than it is in C (§1.3.3). However, goodC programs tend to be C++ programs.

For example, every program in Kernighan and Ritchie, TheC Programming Language, Second Edition [Kernighan,1988], is a C++ program. Experience withany statically typed language will be a help when learning C++.1.2.4 Language, Libraries, and SystemsThe C++ fundamental (built-in) types, operators, and statements are those that computer hardwaredeals with directly: numbers, characters, and addresses. C++ has no built-in high-level data typesand no high-level primitive operations.

For example, the C++ language does not provide a matrixtype with an inversion operator or a string type with a concatenation operator. If a user wants sucha type, it can be defined in the language itself. In fact, defining a new general-purpose or application-specific type is the most fundamental programming activity in C++.

A well-designed userdefined type differs from a built-in type only in the way it is defined, not in the way it is used. TheC++ standard library (Chapter 4, Chapter 5, Chapter 30, Chapter 31, etc.) provides many examplesof such types and their uses. From a user’s point of view, there is little difference between a built-intype and a type provided by the standard library. Except for a few unfortunate and unimportant historical accidents, the C++ standard library is written in C++.

Writing the C++ standard library inC++ is a crucial test of the C++ type system and abstraction mechanisms: they must be (and are)sufficiently powerful (expressive) and efficient (affordable) for the most demanding systems programming tasks. This ensures that they can be used in large systems that typically consist of layerupon layer of abstraction.Features that would incur run-time or memory overhead even when not used were avoided.

Forexample, constructs that would make it necessary to store ‘‘housekeeping information’’ in everyobject were rejected, so if a user declares a structure consisting of two 16-bit quantities, that structure will fit into a 32-bit register. Except for the new, delete, typeid, dynamic_cast, and throw operators, and the try-block, individual C++ expressions and statements need no run-time support.

Thiscan be essential for embedded and high-performance applications. In particular, this implies thatthe C++ abstraction mechanisms are usable for embedded, high-performance, high-reliability, andreal-time applications. So, programmers of such applications don’t have to work with a low-level(error-prone, impoverished, and unproductive) set of language features.C++ was designed to be used in a traditional compilation and run-time environment: the C programming environment on the UNIX system [UNIX,1985]. Fortunately, C++ was never restrictedto UNIX; it simply used UNIX and C as a model for the relationships among language, libraries,compilers, linkers, execution environments, etc. That minimal model helped C++ to be successfulon essentially every computing platform.

There are, however, good reasons for using C++ in environments that provide significantly more run-time support. Facilities such as dynamic loading,incremental compilation, and a database of type definitions can be put to good use without affectingthe language.16Notes to the ReaderChapter 1Not every piece of code can be well structured, hardware-independent, easy to read, etc. C++possesses features that are intended for manipulating hardware facilities in a direct and efficientway without concerns for safety or ease of comprehension. It also possesses facilities for hidingsuch code behind elegant and safe interfaces.Naturally, the use of C++ for larger programs leads to the use of C++ by groups of programmers.

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

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

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

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