Utah Code Camp, Spring 2016. http://utahcodecamp.com In this presentation I describe modern C++. Modern C++ assumes features introduced in the C++11/14 standard. An overview of the new features is presented and some idioms for mdoern C++ based on those features are presented.
2. Thanks to our Sponsors!
Community Sponsor
Yearly Sponsor
Marquee Sponsor
3. About Me...
Meetup organizer:
Utah C++ Programmers (2nd Wednesday)
Salt Lake City Software Craftsmanship (1st Thursday)
3D Modelers (3rd Tuesday)
C++ language track on exercism.io
Polyglot developer
Currently: C++, JavaScript/NodeJS
Previously: C#, JavaScript/NodeJS, Python, Java
Distantly: C, Perl, FORTRAN, LISP, FORTH, Assembly, TECO
Different languages have their strengths
Leverage strengths where appropriate
4. Why Use C++?
Type safety
Encapsulate necessary unsafe operations
Resource safety
Not all resource management is managing memory
Performance
For some parts of almost all systems, it's important
Predictability
For hard or soft real-time systems
5. Why Use C++?
Teachability
Complexity of code should be proportional to
complexity of the task
Readability
For people and machines ("analyzability")
Direct map to hardware
For instructions and fundamental data types
Zero-overhead abstraction
Classes with constructors and destructors, inheritance,
generic programming, functional programming
techniques
6. ISO Standard for C++
C++98 1998: First ISO standard
C++03 2003: "Bug fix" to C++98 standard
C++11 2011: Major enhancement to language and
library
C++14 2014: Bug fixes and improvements to C++11
C++17 2017? Library additions and bug fixes
7. What is "Modern" C++?
Embrace the improvements brought by C++11/14
Eschew old coding practices based on earlier standards
Avoid like the plague C-style coding practices!
8. Print Sorted Words from Input
#include <algorithm> // sort
#include <iostream> // cin, cout
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
string input;
while (cin >> input) {
words.push_back(input);
}
sort(begin(words), end(words));
for (auto w : words) {
cout << w << 'n';
}
return 0;
}
one
barney
zoo
betty
fred
alpha
^Z
alpha
barney
betty
fred
one
zoo
9. Some Observations
This code accepts input words bounded only by
available memory.
string is a general-purpose dynamically sized string
class provided by the standard library.
vector is a standard container for any copyable type,
in this case string.
sort is a standard library algorithm that operates
polymorphically on sequences of values, in this case
strings.
begin and end are standard library functions for
iterating over containers, including "raw" arrays.
10. Print Words Custom Sorted
#include <algorithm> // sort
#include <iostream> // cin, cout
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
string input;
while (cin >> input) {
words.push_back(input);
}
sort(begin(words), end(words),
[](auto lhs, auto rhs) {
return lhs[1] < rhs[1];
});
for (auto w : words) {
cout << w << 'n';
}
return 0;
}
zar
betty
one
alpha
^Z
zar
betty
alpha
one
11. More Observations
Standard library algorithms are extensible through
functors (instances of function class objects).
Lambda functions provide succinct syntax for writing
such functors.
Range-based for loop allows for easy enumeration of
all values in a collection.
auto allows us to let the compiler figure out the types.
C++ standard library algorithms are often more
efficient than their C library counterparts, particularly
when customized with application functors.
12. Beyond the Language:
IDEs and Tools
IDEs and tools have also advanced.
Static analysis tools:
Finds common problems in C++ code bases.
Some tools suggest automated fixes for problems.
Refactoring tools:
Visual Studio 2015
Clion
ReSharper for C++
clang-tidy
13. Goals of C++11/14
Maintain stability and compatibility with prior versions.
Prefer introducing new features via the standard library instead
of the core language.
Prefer changes that can evolve programming technique.
Improve C++ to facilitate systems and library design.
Improve type safety by providing safer alternatives to earlier
unsafe techniques.
Increase performance and the ability to work directly with the
hardware.
Provide proper solutions to real-world problems.
Implement the zero-overhead principle, aka "don't pay for what
you don't use".
Make C++ easier to teach and learn.
14. Performance Additions
"Move semantics" improve performance of transfer of
ownership of data.
constexpr generalized constant expressions.
15. Usability Enhancements
Uniform initializer syntax.
Type inference (auto).
Range-based for loop.
Lambda functions and
expressions.
Alternate function syntax
(trailing return type).
Constructor delegation.
Field initializers.
Explicit override and
final.
Null pointer constant
(nullptr, nullptr_t).
Strongly-typed
enumerations.
Right angle bracket.
Template aliases.
Unrestricted unions.
16. Functionality Enhancements
Variadic templates
Variadic macros
New string literals for
Unicode
User-defined literals
Multithreading memory
model
Thread-local storage
Explicitly defaulting or
deleting special member
functions
Type long long int
Static assertions
Generalized sizeof
Control of object alignment
Allow garbage collected
implementations
Attributes
17. Standard Library Enhancements
Upgrades to standard
library components.
Threading facilities.
Tuples.
Hash tables.
Regular expressions.
General-purpose smart
pointers.
Extensible random
number facility.
Reference wrapper.
Polymorphic wrappers for
function objects.
Type traits for
metaprogramming.
Uniform method for
computing the return
type of function objects.
18. Modern C++ Idioms
"Almost always auto"
"No naked new/delete"
"No raw loops"
"No raw owning pointers"
"Uniform initialization"
Embrace Zero-overhead Abstraction
19. Uniform Initialization
Motivation:
Simplify initialization by using a uniform syntax for
initializing values of all types.
int f{3};
string s{"hello, world!"};
Foo g{"constructor", "arguments"};
vector<string> words{"hi", "there"};
20. Almost Always Auto
Motivation:
Let the compiler figure out types as much as is feasible.
auto x = 42;
auto x{42};
Subjective. Some people prefer it; removes the clutter
of types from the code. Others feel that it can obscure
the actual types being used. No supermajority
consensus yet on this idiom.
21. No Naked new/delete
Motivation:
New and delete are low-level heap operations
corresponding to resource allocation. Their low-level
nature can be a source of errors. Therefore, use an
encapsulating class that implements the desired
ownership policy.
unique_ptr<Foo> f{make_unique<Foo>(x, y)};
shared_ptr<Foo> g{make_shared<Foo>(x, y)};
weak_ptr<Foo> h{g};
22. No Raw Owning Pointers
Motivation:
Use a smart pointer class to enforce ownership policies.
Raw pointers and references are still useful for efficiency,
but they no longer represent ownership.
auto pw = make_shared<widget>();
23. No Raw Loops
Motivation:
The standard library algorithms cover most of what you
need to do. With lambdas for customization, using
them is easy. Write your own algorithms in the style of
the standard library when necessary.
Sean Parent, "C++ Seasoning" Going Native 2013
https://channel9.msdn.com/Events/GoingNative/2013
/Cpp-Seasoning
24. Embrace Zero-Overhead
Abstraction
Motivation:
There is no runtime penalty for abstraction, so embrace
it fully.
Create small, focused types to express specific
semantics on top of general types.
Examples: Points, (geometric) Vectors, Matrices for 3D
graphics. Small concrete value types can be as efficient
as inline computation.
25. Practice Modern C++
http://ideone.com
Web-based modern C++ development environment
Quick to experiment, no install, save work for later.
Visual Studio 2015 Community Edition
Full-featured IDE with refactoring support.
Good for full sized projects.
http://exercism.io
Practice modern C++ on a variety of problems and get peer
review and discussion of your solution.