Professional Documents
Culture Documents
C - Today PDF
C - Today PDF
Now that software development is shifting primarily toward mobile and cloud
computing, the venerable C++ programming language is returning to the dominant
position it held during the object-oriented boom of the 1990s. In this O’Reilly
report, you’ll learn why C++ is once again the preferred choice across several
diverse industries, after taking a backseat to Java during the 2000s.
Today
C++ is a complicated beast that’s not easy to learn. But when you need a powerful,
highly portable systems programming language or an application programming
language with uncompromising performance, it’s hard to beat. With the 2011 and
2014 updates, C++ feels like a completely new language, rather than the old C++
with new features bolted on.
Authors Jon Kalb and Gašper Ažman demonstrate how modern C++ (C++11 and C++14)
provides the power, performance, libraries, and tools necessary for massive server
farms as well as low-footprint mobile apps.
n Delve into the modern C++ features that are generating new interest
in the language
The Beast is Back
n Learn why C++ is the only high-level language available on Apple,
Android, and Microsoft mobile devices
n Explore the C++ cloud computing appeal, including performance,
high portability, and low-level hardware control
n See what the future holds for C++ with proposed changes in the
2017 update
Jon Kalb conducts onsite training on C++ best practices and advanced topics.
Over the past two decades, he’s written C++ for companies including Amazon,
Apple, Dow Chemical, Intuit, Lotus, Microsoft, Netscape, Sun, and Yahoo! An
Approved Outside Training Vendor for Scott Meyers’ training materials, Jon is
currently working on Amazon’s search engine at A9.com.
Gašper Ažman is an undercover mathematician masquerading as a software
engineer. On his quest to express ideas precisely, concisely, and with simplicity,
he studies emerging programming languages for new tricks to apply in his C++.
He’s currently taking a hiatus from teaching to work on the Amazon search engine
at A9.com.
Programming Newsletter
Get programming r elated news and content delivered weekly to your inbox.
oreilly.com/programming/newsletter
O’Reilly Radar
Read more insight and analysis about emerging technologies.
radar.oreilly.com
Conferences
Immerse yourself in learning at an upcoming O’Reilly conference.
conferences.oreilly.com
©2015 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. #15305
C++ Today
The Beast Is Back
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. C++ Today, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the authors have used good faith efforts to ensure that the
information and instructions contained in this work are accurate, the publisher and
the authors disclaim all responsibility for errors or omissions, including without
limitation responsibility for damages resulting from the use of or reliance on this
work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is sub‐
ject to open source licenses or the intellectual property rights of others, it is your
responsibility to ensure that your use thereof complies with such licenses and/or
rights.
978-1-491-92758-8
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
iii
5. Digging Deep on Modern C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Type Inference: Auto and Decltype 45
How Move Semantics Support Value-Semantic and
Functional Programming 48
No More Output Parameters 49
Inner Functions with Lambdas 52
Lambdas as a Scope with a Return Value 54
Bibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
iv | Table of Contents
Preface
This book is a view of the C++ world from two working software
engineers with decades of combined experience programming in
this industry. Of course this view is not omniscient, but is filled with
our observations and opinions. The C++ world is vast and our space
is limited, so many areas, some rather large, and others rather inter‐
esting, have been omitted. Our hope is not to be exhaustive, but to
reveal a glimpse of a beast that is ever-growing and moving fast.
v
CHAPTER 1
The Nature of the Beast
In this book we are referring to C++ as a “beast.” This isn’t from any
lack of love or understanding; it comes from a deep respect for the
power, scope, and complexity of the language,1 the monstrous size of
its installed base, number of users, existing lines of code, developed
libraries, available tools, and shipping projects.
For us, C++ is the language of choice for expressing our solutions in
code. Still, we would be the first to admit that users need to mind
the teeth and claws of this magnificent beast. Programming in C++
requires a discipline and attention to detail that may not be required
of kinder, gentler languages that are not as focused on performance
or giving the programmer ultimate control over execution details.
For example, many other languages allow programmers the oppor‐
tunity to ignore issues surrounding acquiring and releasing mem‐
ory. C++ provides powerful and convenient tools for handling
resources generally, but the responsibility for resource management
ultimately rests with the programmer. An undisciplined approach
can have disastrous consequences.
Is it necessary that the claws be so sharp and the teeth so bitey? In
other popular modern languages like Java, C#, JavaScript, and
Python, ease of programming and safety from some forms of
1 When we refer to the C++ language, we mean to include the accompanying standard
library. When we mean to refer to just the language (without the library), we refer to it
as the core language.
1
programmer error are a high priority. But in C++, these concerns
take a back seat to expressive power and performance.
Programming makes for a great hobby, but C++ is not a hobbyist
language.2 Software engineers don’t lose sight of programming ease
of use and maintenance, but when designing C++, nothing has or
will stand in the way of the goal of creating a truly general-purpose
programming language that can be used in the most demanding
software engineering projects.
Whether the demanding requirements are high performance, low
memory footprint, low-level hardware control, concurrency, high-
level abstractions, robustness, or reliable response times, C++ must
be able to do the job with reasonable build times using industry-
standard tool chains, without sacrificing portability across hardware
and OS platforms, compatibility with existing libraries, or readabil‐
ity and maintainability.
Exposure to the teeth and claws is not just the price we pay for this
power and performance—sometimes, sharp teeth are exactly what
you need.
4 For instance, one can (and people do) use virtual functions in C, but few will contest
that p→vtable→foo(p) is clearer than p→foo().
5 Notable peers are the D programming language, Rust, and, to a lesser extent, Google
Go, albeit with a much smaller installed base.
6 Being a superset of C also enhances the ability of C++ to interoperate with other lan‐
guages. Because C’s string and array data structures have no memory overhead, C has
become the “connecting” interface for all languages. Essentially all languages support
interacting with a C interface and C++ supports this as a native subset.
7 http://www.drdobbs.com/parallel/eliminate-false-sharing/217500206
8 For a small sample of applications and operating systems written in C++: http://
www.stroustrup.com/applications.html
Highly Portable
C++ is designed with a specific hardware model in mind, and this
model has minimalistic requirements. This has made it possible to
port C++ tools and code very broadly, as machines built today, from
nanocomputers to number-crunching behemoths, are all designed
to implement this hardware model.
There are one or more C++ tool chains available on almost all com‐
puting platforms.9 C++ is the only high-level language alternative
available on all of the top mobile platforms.10
Not only are the tools available, but it is possible to write portable
code that can be used on all these platforms without rewriting.
With the consideration of tool chains, we have moved from lan‐
guage features to factors outside of the language itself. But these fac‐
tors have important engineering considerations. Even a language
with perfect syntax and semantics wouldn’t have any practical value
if we couldn’t build it for our target platform.
In order for an engineering organization to seriously consider sig‐
nificant adoption of a language, it needs to consider availability of
tools (including analyzers and other non-build tools), experienced
engineers, software libraries, books and instructional material, trou‐
bleshooting support, and training opportunities.
Extra-language factors, such as the installed user base and industry
support, always favor C++ when a systems language is required and
tend to favor C++ when choosing a language for building large-scale
applications.
11 It would be hard to over-emphasize how costly these problems have been in non-
garbage collected languages.
12 It may also stand for Responsibility Acquisition Is Initialization when the concept is
extended beyond just resource management.
Industry Dominance
C++ has emerged as the dominant language in a number of diverse
product categories and industries.13 What these domains have in
common is either a need for a powerful, portable systems-
programming language or an application-programming language
with uncompromising performance. Some domains where C++ is
dominant or near dominant include search engines, web browsers,
game development, system software and embedded computing,
automotive, aviation, aerospace and defense contracting, financial
engineering, GPS systems, telecommunications, video/audio/image
processing, networking, big science projects, and ISVs.14
13 http://www.lextrait.com/vincent/implementations.html
14 Independent software vendors, the people that sell commercial applications for money.
Like the creators of Office, Quicken, and Photoshop.
C: Portable Assembler
In the early 1970s, Dennis Ritchie introduced “C,”1 a programming
language that did for systems programmers what earlier high-level
1 http://cm.bell-labs.co/who/dmr/chist.html
11
languages had done for domain specialists. It turns out that systems
programmers also want to be free of the mind-numbing detail and
lack of portability inherent in assembly-language programming, but
they still required a language that gave them complete control of the
hardware when necessary.
C achieved this by shifting the burden of knowing the arcane details
of specific machines to the compiler writer. It allowed the C pro‐
grammer to ignore these low-level details, except when they mat‐
tered for the specific problem at hand, and in those cases gave the
programmer the control needed to specify details like memory lay‐
outs and hardware details.
C was created at AT&T’s Bell Labs as the implementation language
for Unix, but its success was not limited to Unix. As the portable
assembler, C became the go-to language for systems programmers
on all platforms.
2 http://www.open-std.org/jtc1/sc22/wg21/
3 Most language creators retain control of their creation or give them to standards bodies
and walk away. Stroustrup’s continuing to work on C++ as part of the ISO is a unique
situation.
4 http://www.boost.org/users/proposal.pdf
5 http://boost.org/
6 https://sfconservancy.org/
The 2000s: Java, the Web, and the Beast Nods Off | 15
The addition of a streams-based input/output library made I/O
much more OOP-like, but meant that the language now had two
complete and completely different I/O libraries.
Adding operator overloading to C++ meant that user-defined types
could be made to behave (almost) exactly like built-in types, but it
also added complexity.
The addition of templates greatly expanded the power of the lan‐
guage, but at no small increase in complexity. The STL was an exam‐
ple of the power of templates, but was a complicated library based
on generic programming, a programming paradigm that was not
appreciated or understood by most programmers.
Was all this complexity worth it for a language that combined the
control and performance of portable assembler with the power and
convenience of high-level abstractions? For some, the answer was
certainly yes, but the environment was changing enough that many
were questioning this.
The first decade of the 21st century saw desktop PCs that were pow‐
erful enough that it didn’t seem worthwhile to deal with all this com‐
plexity when there were alternatives that offered OOP with less
complexity.
One such alternative was Java.
As a bytecode interpreted, rather than compiled, language, Java
couldn’t squeeze out all the performance that C++ could, but it did
offer OOP, and the interpreted implementation was a powerful fea‐
ture in some contexts.7
Because Java was compiled to bytecode that could be run on a Java
virtual machine, it was possible for Java applets to be downloaded
and run in a web page. This was a feature that C++ could only
match using platform-specific plug-ins, which were not nearly as
seamless.
So Java was less complex, offered OOP, was the language of the Web
(which was clearly the future of computing), and the only downside
7 “Build once, run anywhere,” while still often not the case with Java, is sometimes much
more useful for deployment than the “write once, build anywhere” type of portability of
C++.
8 Java’s “references” can be null, and can be re-bound, so they are pointers; you just can’t
increment them.
The 2000s: Java, the Web, and the Beast Nods Off | 17
with no new features in either the core language or the standard
library.
After this, the committee released the first and only C++ Technical
Report, called TR1. A technical report is a way for the committee to
tell the community that it considers the content as standard-
candidate material.
The TR1 didn’t contain any change to the core language, but defined
about a dozen new libraries. Almost all of these were libraries from
Boost, so most programmers already had access to them.
After the release of the TR1, the committee devoted itself to releas‐
ing a new update. The new release was referred to as “0x” because it
was obviously going to be released sometime in 200x.
Only it wasn’t. The committee wasn’t slacking off—they were adding
a lot of new features. Some were small nice-to-haves, and some were
groundbreaking. But the new standard didn’t ship until 2011. Long,
long overdue.
The result was that although the committee had been working hard,
it had released little of interest in the 13 years from 1998 to 2011.
We’ll use the history of one group of programmers, the ACCU, to
illustrate the rise and fall of interest in C++. In 1987, The C Users
Group (UK) was formed as an informal group for those who had an
interest in the C language and systems programming. In 1993, the
group merged with the European C++ User Group (ECUG) and
continued as the Association of C and C++ Users.
By the 2000s, members were interested in languages other than C
and C++, and to reflect that, the group changed its name to just the
initials ACCU. Although the group is still involved in and support‐
ing C++ standardization, its name no longer stands for C++, and
members are also exploring other languages, especially C#, Java,
Perl, and Python.9
9 http://accu.org/index.php/aboutus
The 2000s: Java, the Web, and the Beast Nods Off | 19
CHAPTER 3
The Beast Wakes
In this chapter and the next, we are going to be exploring the factors
that drove interest back to C++ and the community’s response to
this growing interest. However, we’d first like to point out that, par‐
ticularly for the community responses, this isn’t entirely a one-way
street. When a language becomes more popular, people begin to
write and talk about it more. When people write and talk about a
language more, it generates more interest.
Debating the factors that caused the C++ resurgence versus the fac‐
tors caused by it isn’t the point of this book. We’ve identified what
we think are the big drivers and the responses, but let’s not forget
that these responses are also factors that drive interest in C++.
21
Modern mobile devices are very powerful computers in their own
right, but they have a new concern for performance: performance per
watt. For a battery-powered mobile device, there is no such thing as
spare cycles.
Earlier we pointed out that C++ is the only high-level language
available1 for all mobile devices running iOS, Android, or Windows.
Is this because Apple, which adopted Objective-C and invented
Swift, is a big fan of C++? Is it because Google, which invented Go
and Dart, is a big fan of C++? Is it because Microsoft, which inven‐
ted C#, is a big fan of C++? The answer is that these companies want
their devices to feature apps that are developed quickly, but are
responsive and have long battery life. That means they need to offer
developers a language with high-level abstraction features (for fast
development) and high performance. So they offer C++.
Cloud-based computers, that is, computers in racks of servers in
some remote data center, are also powerful computers, but even
there we are concerned about performance per watt. In this case, the
concern isn’t dead batteries, but power cost. Power to run the
machines, and power to cool them.
The cloud has made it possible to build enormous systems spanning
hundreds, thousands, or tens of thousands of machines bound to a
single purpose. A modest improvement in speed at those scales can
represent substantial savings in infrastructure costs.
James Hamilton, a vice president and distinguished engineer on the
Amazon Web Services team, reported on a study he did of modern
high-scale data centers.2 He broke the costs down into (in decreasing
order of significance) servers, power distribution & cooling, power,
networking equipment, and other infrastructure. Notice that the top
three categories are all directly related to software performance,
either performance per hardware investment or performance per
watt. Hamilton determined that 88% of the costs are dependent on
performance. A 1% performance improvement in code will almost
produce a 1% cost savings, which for a data center at scale will be a
significant amount of money.
1 C++ is not necessarily the recommended language on mobile platforms but is supported
in one way or another.
2 http://perspectives.mvdirona.com/2010/09/overall-data-center-costs/
3 To the extent that such languages are being used for prototyping, to bring features to
market quickly, or for software that doesn’t need to run at scale, there is still a role for
these languages. But it isn’t in data centers at scale.
4 And much appreciated. In a 2015 survey, Stack Overflow found that C++11 was the
second “most loved” language of its users (after newcomer Swift). http://stackover
flow.com/research/developer-survey-2015
5 https://isocpp.org/tour
6 http://en.wikipedia.org/wiki/C%2B%2B11
10 For some CPUs and/or code cases, it has caught up or passed its competitors.
11 Some examples comparing error messages from Clang with old and newer versions of
GCC: https://gcc.gnu.org/wiki/ClangDiagnosticsComparison
12 http://clang.llvm.org/docs/AddressSanitizer.html
13 http://clang.llvm.org/docs/MemorySanitizer.html
14 http://clang.llvm.org/docs/LeakSanitizer.html
15 http://clang.llvm.org/docs/ThreadSanitizer.html
16 https://metashell.readthedocs.org/en/latest/
17 http://lcamtuf.coredump.cx/afl/
18 https://dxr.readthedocs.org/en/latest/
19 Clang and its standard library implementation, libc++, are usually the first compiler
and library to implement new C++ features.
20 The JIT has the ability to see the entire application. This allows for optimizations that
would not be possible to a compiler linking to compiled library object files. Today’s
C++ compilers use link-time (or whole-program) optimization features to achieve
these optimizations. This requires that object files be compiled to support this feature.
On the other hand, the JIT compiler was hampered by the very dynamic nature of Java,
which forbade most of the optimizations the C++ compiler can do.
WG21
Our first topic is the ISO Committee for C++ standardization,
which at 25 years old, is hardly a new resource, but it certainly glows
with new life. The committee is formally called ISO/IEC JTC1 (Joint
Technical Committee 1) / SC22 (Subcommittee 22) / WG21 (Work‐
ing Group 21).1 Now you know why most people just call it the C++
Standards Committee.
As big an accomplishment as it is to release a new or updated major
standard like C++98 or C++11, it doesn’t have much practical
impact if there are no tools that implement it. As mentioned earlier,
this was a significant issue with the release of the standard in 1998.
Committee attendance fell off because implementation was under‐
stood to be years away.
But this was not the case for the release in 2011. Tool vendors had
been tracking the standard as it was being developed. Although it
called for significant changes to both the core language and the stan‐
1 https://isocpp.org/std/the-committee
31
dard library, the new update was substantially implemented by a
couple of different open source implementations, GCC and Clang,
soon after its release.2 Other tool vendors had also demonstrated
their commitment to the update. Unlike some language updates,3
this was clearly adopted by the entire community as the path for‐
ward.
The psychological impact of this should not be underestimated.
Thirteen years is a very long time in the world of programming lan‐
guages. Some people had begun to think of C++ as an unchanging
definition, like chess or Latin. The update changed the perception of
C++ from a dying monster of yesteryear into a modern, living crea‐
ture.
The combination of seeing C++ as a living creature, and one where
implementations closely followed4 standardization, meant that
Standards Committee meeting attendance began to increase.5
The committee reformulated itself6 to put the new members to the
best use. It had long been formed of a set of subcommittees called
working groups. There were Core, Library, and Evolution working
groups; but with many new members and so many areas in which
the industry is asking for standardization, new working groups were
the answer. The Committee birthed over a dozen new “Domain Spe‐
cific Investigation & Development” groups.
The first new product of the committee was a new standard in 2014.
C++14 was not as big a change as C++11, but it did significantly
improve some of the new features in C++11 by filling in the gaps
discovered with real-world experience using these new features.
The target for the next standard release is 2017. The working groups
are busy reviewing and developing suggestions that may or may not
become part of the next update.
2 Note the weasel words “substantially” and “soon.” Complete and bug-free implementa‐
tions of every feature aren’t the point here. The crux is that the community recognized
that C++11 was a real thing and the need to get on board right away.
3 We are looking at you, Python 3.0.
4 Or, in the case of some features, preceded.
5 The meeting where a new standard is officially voted to be a release is always highly
attended. The first few meetings after that did see a bit of a drop, but soon the upward
trend was clear.
6 https://isocpp.org/std/the-committee
Tools
Clang is clearly the most significant new development in the C++
toolchain, but the resurgence of interest in C++ has brought more
than just Clang to the community. We’ll discuss a few interesting
newcomers.
biicode7 is a cross-platform dependency manager that you can use to
download, configure, install, and manage publicly available libraries,
like the Boost libraries. This is old-hat for other languages, but this
is new technology for C++. The site only hit 1.0 in the middle of
2014 and is still in beta, but it has thousands of users and has been
growing aggressively.
Undo Software8 has a product called UndoDB, which is a reversible
debugger. The idea of a reversible debugger, one that supports step‐
ping backward in time, is so powerful that it has been implemented
many times. The problem with previous implementations is that
they run so slowly and require so much data collection that they
aren’t practical for regular use. Undo has found a way to increase the
speed and reduce the data requirements so that the approach is
practical for the first time. This product isn’t C++ only, but its mar‐
keting is focused on the C++ community.
JetBrains9 has built its reputation on IDEs with strong refactoring
features and has over a dozen products for developers. But until
launching CLion10 in 2015, it’s not had a C++ product. CLion is a
cross-platform IDE for C and C++ with support for biicode. CLion
can be used on Windows, but for developers that use Microsoft’s
7 https://www.biicode.com/
8 http://undo-software.com/
9 https://www.jetbrains.com/
10 https://www.jetbrains.com/clion/
Tools | 33
Visual Studio for C++ development, JetBrains is updating
ReSharper,11 its VS extension, which supports C#, .NET, and web-
development languages to also support C++.
The last tool that we’ll mention isn’t a development tool, but a
deployment tool. OSv 12 is an operating system written in C++ that is
optimized for use in the cloud. By rethinking the requirements of a
virtual machine existing in the cloud, Cloudius Systems has created
an OS with reduced memory and CPU overhead and lightweight
scheduling. Why was this implemented in C++ instead of C? It turns
out that gets asked a lot:
While C++ has a deserved reputation for being incredibly compli‐
cated, it is also incredibly rich and flexible, and in particular has a
very flexible standard library as well as add-on libraries such as
boost. This allows OSV code to be much more concise than it
would be if it were written in C, while retaining the close-to-the-
metal efficiency of C.13
—OSv FAQ
11 https://www.jetbrains.com/resharper/
12 http://osv.io/
13 http://osv.io/frequently-asked-questions/
14 Consider Java, JavaScript, C#, Objective-C.
15 It gave the rights to the C++ manual to the ISO. http://www.stroustrup.com/
bs_faq.html#revenues
16 The only central organization for C++ was the Standards Committee, but promoting
the language was outside of its charter (and resources).
23 https://isocpp.org/get-started
24 https://isocpp.org/wiki/faq/user-groups-worldwide
Q&A
The Internet revolution has changed the practical experience of
writing code in any language. The combination of powerful public
search engines and websites with reference material and thousands
of questions and answers dramatically reduces the time lag between
needing an answer about a particular language feature, library call,
or programming technique, and finding that answer.
The impact is disproportionately large for languages that are very
complicated, have a large user base (and therefore lots of online
resources) or, like C++, both. Here are some online resources that
C++ programmers have found useful.
Nate Kohl noticed that there were some sites with useful references
for other languages,34 so in 2000, he launched cppreference.com.35
Initially he posted documentation as static content that he main‐
tained himself. From the beginning, there were some contributions
from across the Internet, but in 2008, the contribution interest was
too much to be manageable, so he converted the site to a wiki.
Kohl’s approach is to start with high-level descriptions and present
increasing detail that people can get into if they happen to be inter‐
ested. His theory is that examples are more useful to people trying
to solve a problem quickly than rigorous formal descriptions.
The wiki has the delightful feature that all the examples are compila‐
ble right there on the website. You can modify the example and then
run it to see the result. Right there on the wiki!
32 http://en.wikipedia.org/wiki/Category:C%2B%2B_libraries
33 http://en.cppreference.com/w/cpp/links/libs
Q&A | 37
As useful as documentation and examples are, some people learn
better in a question-and-answer format. In 2008, Stack Overflow36
launched as a resource for programmers to get their questions
answered. Stack Overflow allows users to submit questions about all
kinds of programming topics and currently contains over 300,000
answered questions on C++.
In order for a Q&A site to be useful, it needs to provide a good way
to find the question you are looking for, and high-quality answers.
Your favorite Internet search engine does pretty well with Stack
Overflow, and the answers tend to be of high quality. Post a ques‐
tion, and it might be answered by Jonathan Wakely, Howard Hin‐
nant, James McNellis, Dietmar Kühl, Sebastian Redl, Anthony
Williams, Eric Niebler, or Marshall Clow. These are the people that
have built the libraries you are asking about.
As useful as a Q&A site like Stack Overflow is, some people feel
more comfortable in a more traditional forum environment. Alex
Allain, who wrote the book Jumping into C++ [JIC] has built cprog‐
ramming.com37 into a community site of its own with references,
tutorials, book reviews, tips, problems, quizes, and several forums.
Of course, for those that like their Q&A retro style, some usernet
groups still exists for C++: comp.lang.c++,38 comp.lang.c++.moder‐
ated,39 and comp.std.c++.40
As you’d expect of a language with a large user base, there are a lot of
Internet hangouts for learning about and discussing C++. There are
dozens of blogs41 and an active subreddit.42 Jens Weller maintains a
blog at Meeting C++ called Blogroll that is a weekly list of the latest
C++ blogs.43
36 http://stackoverflow.com/questions/tagged/c%2b%2b
37 http://cprogramming.com
38 https://groups.google.com/forum/!forum/comp.lang.c++.moderated
39 https://groups.google.com/forum/!forum/comp.lang.c++.moderated
40 https://groups.google.com/forum/#!forum/comp.std.c++
41 http://www.quora.com/What-are-the-best-blogs-on-C++
42 http://www.reddit.com/r/cpp/
43 http://meetingcpp.com/index.php/blogroll.html
44 http://cppandbeyond.com/
45 And D.
46 The registration limit has varied from 60 to 120, depending on the venue. The 2010
event was so popular an “encore” event was held a couple of months later.
47 The same.
48 BoostCon always had two tracks. Initially, the plan was that one track was for Boost
Library developers and the other for users. Over time this distinction was lost, but the
conference continued to have two tracks.
49 http://meetingcpp.com/
Videos
The CppCon session videos supplement an amazing amount of
high-quality video content on C++. Most of the C++ conferences
mentioned earlier have posted some or all of their sessions online
free. The BoostCon YouTube channel54 has sessions from both
50 Weller also blogs regularly about the proposal papers for each standards meeting:
http://meetingcpp.com/index.php/blog.html
51 http://meetingcpp.com/index.php/user-groups.html
52 https://isocpp.org/wiki/faq/user-groups-worldwide
53 After publishing the videos on YouTube, the conference received requests for an alter‐
native from developers in countries where YouTube is blocked. So the conference asked
Microsoft’s Channel 9 to host them as well.
54 https://www.youtube.com/user/Boostcon
Videos | 41
BoostCon and C++Now. Both Meeting C++55 and CppCon56 have
YouTube channels as well.
Channel 9, Microsoft’s developer information channel, makes its
videos available in a wide variety of formats, including audio-only
for listening on the go. In addition to hosting the CppCon videos,57
some sessions from C++ and Beyond in 201158 and 2012,59 all of the
sessions of the two GoingNative conferences in 201260 and 2013,61
and a number of other videos on C++,62 Channel 9 also has a series
on C++ that is called C9::GoingNative.63
If your tastes or requirements run more toward formal training,
there are some good C++ courses on both pluralsight64 and udemy.65
CppCast
Although there are lots of C++ videos, there is relatively little
audio.66 This follows from the fact that when discussing C++, we
almost always want to look at code, which doesn’t work well with
just audio. But audio does work for interviews, and Rob Irving has
launched CppCast,67 the only podcast dedicated to C++.
Books
There are hundreds of books on C++, but in an era of instant Inter‐
net access to thousands of technical sites and videos of almost every
55 https://www.youtube.com/user/MeetingCPP
56 https://www.youtube.com/user/CppCon
57 http://channel9.msdn.com/Events/CPP/C-PP-Con-2014
58 http://channel9.msdn.com/Tags/cppbeyond+2011
59 http://channel9.msdn.com/Tags/cppbeyond+2012
60 http://channel9.msdn.com/Events/GoingNative/GoingNative-2012
61 http://channel9.msdn.com/Events/GoingNative/2013
62 http://channel9.msdn.com/Tags/c++
63 http://channel9.msdn.com/Shows/C9-GoingNative
64 http://www.pluralsight.com/tag/c++
65 https://www.udemy.com/courses/search/?q=c%2B%2B
66 Although Channel 9 content is available as audio-only, this tends to work well only for panels and interviews.
67 http://cppcast.com/
Here are a couple of books that are new, not updates of classic C++
versions:
Scott Meyers’ Effective Modern C++: 42 Specific Ways to Improve
Your Use of C++11 and C++14 [EMC] was one of the most eagerly
awaited books in the community. An awful lot of today’s C++ pro‐
68 http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876/
69 http://scottmeyers.blogspot.de/2011/03/effective-c-in-c0x-c11-age.html
70 https://isocpp.org/tour
Books | 43
grammers feel like the Effective C++ series was a formative part of
our C++ education, and we’ve wanted to know for a long time what
Scott’s take on the new standard would be. Now we can find out.
Unlike the previously mentioned books, Anthony Williams’ C++
Concurrency in Action: Practical Multithreading [CCIA] is not about
C++ generally, but just focuses on the new concurrency features
introduced in C++11. The author is truly a concurrency expert. Wil‐
liams has been the maintainer of the Boost Thread library since
2006, and is the developer of the just::thread implementation of the
C++11 thread library. He also authored many of the papers that
were the basis of the thread library in the standard.
The power of the additional features that were introduced with the
2011 and 2014 updates comes not just from the changes, but from
the way these changes integrate with classic features. This is the pri‐
mary reason the update feels like a whole new language, rather than
a version of classic C++ with a collection of new features bolted on.
In this chapter, we will demonstrate what that means, which
requires looking at some code. Feel free to skip this chapter if your
interest in C++ is not as a coder.
45
// read lines from stdin
// write sorted unique lines to stdout
int main(int argc, char** argv) {
using std::vector; using std::string; using std::sort;
using std::unique; using std::cin; using std::cout;
vector<string> lines;
while (cin) {
lines.emplace_back();
getline(cin, lines.back());
};
sort(lines.begin(), lines.end());
If this doesn’t seem like a big deal, it’s because it isn’t—in this case.
Still, it breaks the flow of reading code because of completely unnec‐
essary complications. One’s mind wonders if the equivalent Python
would be easier to read.
We can do better with a modern style.
1 While Boost has continualy proven that nothing is impossible (boost::bind comes to
mind), for the vast majority of programmers, unthinkable is much the same thing as
impossible.
2 Before C++11, one had to use std::copy to transfer the results into an output iterator,
which in this case would be a std::ostream_iterator<string>(cout, "\n"), but this
is inelegant and rather inflexible compared to just using a for loop, since writing out‐
put iterators for every purpose is rather involved, not to mention verbose.
3 In functional programming, functions do not modify global state or the state of their
parameters. Computational results are exclusively captured by return values. https://
wiki.haskell.org/Functional_programming
4 For performance-obsessed C++ programmers, issues like this could make functional
programming a nonstarter.
In the snippet, there are no copies at all. As a final step, the result is
moved back into lines.6 This is just as efficient as the procedural
version, while the functions, as implemented, supply all of the
advantages of reasoning about code that come with a pure-
functional style.
The ranged for loop is as easy to write as it would be in Python, but
without performance loss.
Example 5-7. Ranged for loops can iterate over function return values
for (auto const& line : uniqued(sorted(std::move(lines)))) {
cout << line << '\n';
}
5 If the copy is not elided entirely. “Elided” is standard-speak for a copy omitted as
unnecessary.
6 Should we have needed lines to be untouched, we would have assigned to a different
variable and not used the move().
Example 5-8. Compute the length, min, and max of the values
template <typename ConstInputIterator,
typename MinMaxType =
iterator_value_type<ConstInputIterator>>
auto lenminmax(ConstInputIterator first, ConstInputIterator last)
-> std::tuple<size_t, MinMaxType, MinMaxType> {
if (first == last) { return {0, 0, 0}; }
size_t count{1};
auto minimum(*first);
auto maximum(minimum); // only evaluate *first once
while (++first != last) {
++count;
auto const value = *first;
if (value < minimum) {
minimum = value;
} else if (maximum < value) {
maximum = value;
}
}
return {count, minimum, maximum};
}
7 Return value optimization, while explicitly provisioned for by the standard, is not
understood by the majority of programmers and is not applicable in all situations.
Notice how we used tie to assign to min and max and ignore the
length.
There is one more thing to consider: how did we discover the type
of the tuple that lenminmax returns? We seem to use the magical
iterator_value_type to infer the type the iterator returns.8 Logi‐
cally, the type of minimum and maximum is whatever type the itera‐
tor’s reference is: the type of *first.
We can get that type with decltype(*first). Still, that’s not quite
right, because *first returns a reference, and we need a value type.
Fortunately, there is a way to get rid of references in types:
std::remove_reference<T>::type. We just need to supply the type,
which makes std::remove_reference<decltype(*first)>::type.
This is quite a mouthful, so we would be better served if we could
make a type alias for it. However, in the type alias, we cannot use
"first" because the name is not defined outside of the function.
Still, we need some kind of value inside the decltype to dereference.
Again, the standard library has what we need: declval<T>().
declval<T>() gives us a fictional reference to use inside decltype
in place of first. The result is in the next example.
8 In the olden days, we would rely on iterator traits, which generated much confusion in
teaching, and required library authors to provide them for their structures, which did
not always happen.
Now, we can just use it everywhere, like in the definition of the len
minmax function.
Also notice that we were able to give the part of the algorithm that
drains the final remaining sequence into the output sequence a
name, even though the actual implementation is only one line. Every
part of the algorithm reads cleanly.
This is also a great example of the difference in style between inner
functions and regular functions. This much mutation, in-out
parameters, etc., are extremely poor style when designing function
signatures, because the implementation might be far from the point
of use. In most contexts, in-out parameters cause higher cognitive
load for the programmer, making bugs and slowdowns more proba‐
ble.
However, inner functions are not public, and their implementation
is close at hand—it is in the same scope! Here, in-out parameters do
not cause higher cognitive load. Instead, they help us understand
thread producer([&]{
for (int i = 0; i < 1000; ++i) {
{
unique_lock<mutex> lock{queue_mutex};
queue.push_back(i);
}
// one must release the lock before notifying
queue_changed.notify_all();
Most often, you will want to encapsulate this logic into a class, but it
is exceedingly hard to design general queuing interfaces that are
nevertheless fast in all scenarios. Sometimes, an ad hoc approach is
exactly what is needed, such as in a book, where the limit is a page.
Without the gratuitous use of lambda functions, this code would be
longer and less clear.
We don’t claim any particular gifts at seeing the future, but we can
peak at where the standard is going, and then we’ll point out some
of the trends that we see today that we think will continue to be
important, perhaps even more important in the future.
57
This can support dramatically faster builds and better encapsu‐
lation of libraries.
File System
It currently isn’t possible to read the contents of a directory in a
standard portable way. This group is looking at the Boost File‐
System library.
Networking (Inactive1)
Currently all networking done in C++ (and there is a lot) is
done with nonportable libraries. It is time that networking is
part of the standard.
Transactional Memory
The future is concurrency, but “locks” don’t compose or scale.
Transactional memory is one possible solution.2
Numerics
Fortran is often seen as the language of choice for programs
requiring extensive numeric computations, particularly if
matrixes are required. The Standards Committee isn’t willing to
cede this domain.
Reflection
C++ reflection is limited. It is likely to continue to be restricted
to compile time, but there are a lot of opportunities for
improvement even with this limitation.
Concepts
Investigating how to define constraints on types used in generic
programming.
Ranges
Investigating how to update the standard library with a range
concept rather than iterator pairs and how to extend this to
include containers and range-based algorithms.
Feature Test
Standard features are rolled out as fast as tool vendors can pro‐
vide them. This group is looking at how to define a portable
standard way to check for the presence of new features.
6 It worked well with the TR1 from 2005 that was incorporated into the 2011 release with
some minor changes. But that was library-only, and almost all of it was already imple‐
mented and in wide usage as Boost libraries.
7 The approach will also fail if users embrace the TS in such a way that it becomes a de
facto standard of its own.
8 File System
Performance
Mobile and cloud computing has rekindled the interest in perfor‐
mance, and we think performance will always be important. No
computer will ever be powerful or energy efficient enough that per‐
formance won’t matter, at least for some very important applica‐
tions. This looks good for a language that has always been
uncompromising in its approach to performance.
New Platforms
As the cost of hardware falls, more and more computing devices will
be created. These new devices will mean new environments, some
with very tight memory footprint requirements. This looks good for
a highly portable systems language with a “you don’t pay for what
you don’t use” approach to features.
Scale
At the top end, the falling cost of hardware will lead to the design
and implementation of systems of a size that are difficult for us to
imagine now. To implement these systems, engineers are going to
9 There is not even any guarantee that next standard will be released in 2017.
10 “If something cannot go on forever, it will stop." — Herbert Stein
Software Ubiquity
Our world is going to be more and more one in which we are sur‐
rounded by software. Will all of this software need to be highly
portable, low-memory, high-performance code? Of course not.
There will be great demand for applications that do not require soft‐
ware to be pushed to the limit. But these applications will always run
on infrastructure where performance will be in demand. A lot of
this infrastructure is currently written in C, but when infrastructure
code requires high-level abstractions, that code is and will usually be
written in C++.
It may be that the software industry as a whole will grow faster than
the C++ community and that shrinking market share may make
C++ appear to be less important. But the fact is that high perfor‐
mance infrastructure makes it possible to create applications in a
less demanding programming environment. More programmers
working in high-level, nonsystems languages just increases the
demand for and value of the systems-programming projects that
make their work possible.
Powerful Tools
The philosophy of C++ has been to rely more and more on a power‐
ful compiler to do the heavy lifting of making high-performance
applications. At times, that has pushed our compilers to the break‐
ing point.11 We think this is the correct direction for tool develop‐
ment: designing tools that let programmers focus on expressing
their ideas as clearly as possible, and let the tools do the hard work
to implement these ideas efficiently.
11 Early users of code that pushed the envelope on templates sometimes found that their
compilers seemed to grind to a halt. Advances in compiler technology and computing
power generally overcame this limitation.
65
About the Authors
Jon Kalb does on-site training on C++ best practices and advanced
topics. He is an Approved Outside Training Vendor for Scott Mey‐
ers’ training materials and is an award-winning conference speaker.
For information on course content, dates, and rates, please email
jon@cpp.training.
Jon has been programming in C++ for two and a half decades. He is
currently working on Amazon’s search engine at A9.com. During
the last 25 years, he has written C++ for Amazon, Apple, Dow
Chemical, Intuit, Lotus, Microsoft, Netscape, Sun, Yahoo!, and a
number of companies that you’ve not heard of.
Gašper Ažman is an undercover mathematician masquerading as a
software engineer. On his quest to express ideas precisely, concisely,
and with great care for simplicity, he likes to study emerging pro‐
gramming languages for new tricks to apply in his C++. He is cur‐
rently taking a hiatus from teaching to work on the Amazon search
engine at A9.com. In his free time, he makes music and bread.
12 Hanabusa Itchō