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

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

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

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

These are featuresthat will be pervasive in good code. Their major role is to flesh out the C++ feature set to bettersupport programming styles (§1.2.1). They are the foundation of the synthesis that is C++11.Much work went into a proposal that did not make it into the standard. ‘‘Concepts’’ was a facility for specifying and checking requirements for template arguments [Gregor,2006] based on previous research (e.g., [Stroustrup,1994] [Siek,2000] [DosReis,2006]) and extensive work in the committee. It was designed, specified, implemented, and tested, but by a large majority the committeedecided that the proposal was not yet ready.

Had we been able to refine ‘‘concepts,’’ it would havebeen the most important single feature in C++11 (its only competitor for that title is concurrencysupport). However, the committee decided against ‘‘concepts’’ on the grounds of complexity, difficulty of use, and compile-time performance [Stroustrup,2010b]. I think we (the committee) did theright thing with ‘‘concepts’’ for C++11, but this feature really was ‘‘the one that got away.’’ This iscurrently a field of active research and design [Sutton,2011] [Stroustrup,2012a].1.4.4.2 Standard LibraryThe work on what became the C++11 standard library started with a standards committee technicalreport (‘‘TR1’’). Initially, Matt Austern was the head of the Library Working Group, and laterHoward Hinnant took over until we shipped the final draft standard in 2011.As for language features, I’ll only list a few standard-library components with references to thetext and the names of the individuals most closely associated with them.

For a more detailed list,see §44.2.2. Some components, such as unordered_map (hash tables), were ones we simply didn’tmanage to finish in time for the C++98 standard. Many others, such as unique_ptr and functionwere part of a technical report (TR1) based on Boost libraries. Boost is a volunteer organizationcreated to provide useful library components based on the STL [Boost].• Hashed containers, such as unordered_map: §31.4.3; Matt Austern.• The basic concurrency library components, such as thread, mutex, and lock: §5.3, §42.2; PeteBecker, Peter Dimov, Howard Hinnant, William Kempf, Anthony Williams, and more.• Launching asynchronous computation and returning results, future, promise, and async():§5.3.5, §42.4.6; Detlef Vollmann, Lawrence Crowl, Bjarne Stroustrup, and Herb Sutter.• The garbage collection interface: §34.5; Michael Spertus and Hans Boehm.• A regular expression library, regexp: §5.5, Chapter 37; John Maddock.• A random number library: §5.6.3, §40.7; Jens Maurer and Walter Brown.

It was about time.I shipped the first random number library with ‘‘C with Classes’’ in 1980.Several utility components were tried out in Boost:• A pointer for simply and efficiently passing resources, unique_ptr: §5.2.1, §34.3.1; HowardE. Hinnant. This was originally called move_ptr and is what auto_ptr should have been hadwe known how to do so for C++98.• A pointer for representing shared ownership, shared_ptr: §5.2.1, §34.3.2; Peter Dimov. Asuccessor to the C++98 counted_ptr proposal from Greg Colvin.30Notes to the Reader•••Chapter 1The tuple library: §5.4.3, §28.5, §34.2.4.2; Jaakko Jarvi and Gary Powell.

They credit along list of contributors, including Doug Gregor, David Abrahams, and Jeremy Siek.The general bind(): §33.5.1; Peter Dimov. His acknowledgments list a veritable who’s whoof Boost (including Doug Gregor, John Maddock, Dave Abrahams, and Jaakko Jarvi).The function type for holding callable objects: §33.5.3; Doug Gregor. He credits WilliamKempf and others with contributions.1.4.5 What is C++ used for?By now (2013), C++ is used just about everywhere: it is in your computer, your phone, your car,probably even in your camera. You don’t usually see it. C++ is a systems programming language,and its most pervasive uses are deep in the infrastructure where we, as users, never look.C++ is used by millions of programmers in essentially every application domain.

Billions(thousands of millions) of lines of C++ are currently deployed. This massive use is supported byhalf a dozen independent implementations, many thousands of libraries, hundreds of textbooks, anddozens of websites. Training and education at a variety of levels are widely available.Early applications tended to have a strong systems programming flavor. For example, severalearly operating systems have been written in C++: [Campbell,1987] (academic), [Rozier,1988](real time), [Berg,1995] (high-throughput I/O). Many current ones (e.g., Windows, Apple’s OS,Linux, and most portable-device OSs) have key parts done in C++.

Your cellphone and Internetrouters are most likely written in C++. I consider uncompromising low-level efficiency essentialfor C++. This allows us to use C++ to write device drivers and other software that rely on directmanipulation of hardware under real-time constraints. In such code, predictability of performanceis at least as important as raw speed.

Often, so is the compactness of the resulting system. C++was designed so that every language feature is usable in code under severe time and space constraints (§1.2.4) [Stroustrup,1994,§4.5].Some of today’s most visible and widely used systems have their critical parts written in C++.Examples are Amadeus (airline ticketing), Amazon (Web commerce), Bloomberg (financial information), Google (Web search), and Facebook (social media).

Many other programming languagesand technologies depend critically on C++’s performance and reliability in their implementation.Examples include the most widely used Java Virtual Machines (e.g., Oracle’s HotSpot), JavaScriptinterpreters (e.g., Google’s V8), browsers (e.g., Microsoft’s Internet Explorer, Mozilla’s Firefox,Apple’s Safari, and Google’s Chrome), and application frameworks (e.g., Microsoft’s .NET Webservices framework). I consider C++ to have unique strengths in the area of infrastructure software[Stroustrup,2012a].Most applications have sections of code that are critical for acceptable performance.

However,the largest amount of code is not in such sections. For most code, maintainability, ease of extension, and ease of testing are key. C++’s support for these concerns has led to its widespread use inareas where reliability is a must and where requirements change significantly over time. Examplesare financial systems, telecommunications, device control, and military applications.

For decades,the central control of the U.S. long-distance telephone system has relied on C++, and every 800 call(i.e., a call paid for by the called party) has been routed by a C++ program [Kamath,1993]. Manysuch applications are large and long-lived. As a result, stability, compatibility, and scalability havebeen constant concerns in the development of C++. Multimillion-line C++ programs are common.Section 1.4.5What is C++ used for?31Games is another area where a multiplicity of languages and tools need to coexist with a language providing uncompromising efficiency (often on ‘‘unusual’’ hardware).

Thus, games has beenanother major applications area for C++.What used to be called systems programming is widely found in embedded systems, so it is notsurprising to find massive use of C++ in demanding embedded systems projects, including computer tomography (CAT scanners), flight control software (e.g., Lockheed-Martin), rocket control,ship’s engines (e.g., the control of the world’s largest marine diesel engines from MAN), automobile software (e.g., BMW), and wind turbine control (e.g., Vesta).C++ wasn’t specifically designed with numerical computation in mind. However, much numerical, scientific, and engineering computation is done in C++. A major reason for this is that traditional numerical work must often be combined with graphics and with computations relying ondata structures that don’t fit into the traditional Fortran mold (e.g., [Root,1995]).

I am particularlypleased to see C++ used in major scientific endeavors, such as the Human Genome Project,NASA’s Mars Rovers, CERN’s search for the fundamentals of the universe, and many others.C++’s ability to be used effectively for applications that require work in a variety of applicationareas is an important strength. Applications that involve local- and wide-area networking, numerics, graphics, user interaction, and database access are common.

Traditionally, such applicationareas were considered distinct and were served by distinct technical communities using a variety ofprogramming languages. However, C++ is widely used in all of those areas, and more. It isdesigned so that C++ code can coexist with code written in other languages. Here, again, C++’sstability over decades is important. Furthermore, no really major system is written 100% in a single language.

Thus, C++’s original design aim of interoperability becomes significant.Major applications are not written in just the raw language. C++ is supported by a variety oflibraries (beyond the ISO C++ standard library) and tool sets, such as Boost [Boost] (portable foundation libraries), POCO (Web development), QT (cross-platform application development),wxWidgets (a cross-platform GUI library), WebKit (a layout engine library for Web browsers),CGAL (computational geometry), QuickFix (Financial Information eXchange), OpenCV (real-timeimage processing), and Root [Root,1995] (High-Energy Physics).

There are many thousands ofC++ libraries, so keeping up with them all is impossible.1.5 AdviceEach chapter contains an ‘‘Advice’’ section with a set of concrete recommendations related to itscontents. Such advice consists of rough rules of thumb, not immutable laws. A piece of adviceshould be applied only where reasonable. There is no substitute for intelligence, experience, common sense, and good taste.I find rules of the form ‘‘never do this’’ unhelpful.

Consequently, most advice is phrased assuggestions for what to do. Negative suggestions tend not to be phrased as absolute prohibitionsand I try to suggest alternatives. I know of no major feature of C++ that I have not seen put to gooduse. The ‘‘Advice’’ sections do not contain explanations. Instead, each piece of advice is accompanied by a reference to an appropriate section of the book.For starters, here are a few high-level recommendations derived from the sections on design,learning, and history of C++:32Notes to the ReaderChapter 1[1]Represent ideas (concepts) directly in code, for example, as a function, a class, or an enumeration; §1.2.[2] Aim for your code to be both elegant and efficient; §1.2.[3] Don’t overabstract; §1.2.[4] Focus design on the provision of elegant and efficient abstractions, possibly presented aslibraries; §1.2.[5] Represent relationships among ideas directly in code, for example, through parameterization or a class hierarchy; §1.2.1.[6] Represent independent ideas separately in code, for example, avoid mutual dependenciesamong classes; §1.2.1.[7] C++ is not just object-oriented; §1.2.1.[8] C++ is not just for generic programming; §1.2.1.[9] Prefer solutions that can be statically checked; §1.2.1.[10] Make resources explicit (represent them as class objects); §1.2.1, §1.4.2.1.[11] Express simple ideas simply; §1.2.1.[12] Use libraries, especially the standard library, rather than trying to build everything fromscratch; §1.2.1.[13] Use a type-rich style of programming; §1.2.2.[14] Low-level code is not necessarily efficient; don’t avoid classes, templates, and standardlibrary components out of fear of performance problems; §1.2.4, §1.3.3.[15] If data has an invariant, encapsulate it; §1.3.2.[16] C++ is not just C with a few extensions; §1.3.3.In general: To write a good program takes intelligence, taste, and patience.

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

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

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

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