Modern C++

Post on 13-Apr-2017

389 views 0 download

transcript

Modern C++Richard Thomson

Principal Architect for Modeling, Daz 3Dlegalize@xmission.com

@LegalizeAdulthdLegalizeAdulthood.wordpress.com

Thanks to our Sponsors!Community Sponsor

Yearly Sponsor

Marquee Sponsor

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.ioPolyglot developer

Currently: C++, JavaScript/NodeJSPreviously: C#, JavaScript/NodeJS, Python, JavaDistantly: C, Perl, FORTRAN, LISP, FORTH, Assembly,

TECODifferent languages have their strengthsLeverage strengths where appropriate

Why Use C++?Type safety

Encapsulate necessary unsafe operationsResource safety

Not all resource management is managing memory

PerformanceFor some parts of almost all systems, it's

importantPredictability

For hard or soft real-time systems

Why Use C++?Teachability

Complexity of code should be proportional to complexity of the task

ReadabilityFor people and machines ("analyzability")

Direct map to hardwareFor instructions and fundamental data types

Zero-overhead abstractionClasses with constructors and destructors,

inheritance, generic programming, functional programming techniques

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

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!

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

barneyzoobettyfredalpha^Zalphabarneybettyfredonezoo

Some ObservationsThis 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.

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;}

zarbettyonealpha^Zzarbettyalphaone

More ObservationsStandard 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.

Beyond the Language:IDEs and ToolsIDEs 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 2015ClionReSharper for C++clang-tidy

Goals of C++11/14Maintain 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.

Performance Additions"Move semantics" improve performance of

transfer of ownership of data.

constexpr generalized constant expressions.

Usability EnhancementsUniform 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.

Functionality EnhancementsVariadic templatesVariadic macrosNew string literals for

UnicodeUser-defined literalsMultithreading memory

modelThread-local storageExplicitly defaulting or

deleting special member functions

Type long long intStatic assertionsGeneralized sizeofControl of object

alignmentAllow garbage collected

implementationsAttributes

Standard Library EnhancementsUpgrades 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.

Modern C++ Idioms"Almost always auto"

"No naked new/delete"

"No raw loops"

"No raw owning pointers"

"Uniform initialization"

Embrace Zero-overhead Abstraction

Uniform InitializationMotivation:

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"};

Almost Always AutoMotivation:

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.

No Naked new/deleteMotivation:

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};

No Raw Owning PointersMotivation:

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>();

No Raw LoopsMotivation:

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

Embrace Zero-Overhead AbstractionMotivation:

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.

Practice Modern C++http://ideone.com

Web-based modern C++ development environmentQuick to experiment, no install, save work for later.

Visual Studio 2015 Community EditionFull-featured IDE with refactoring support.Good for full sized projects.

http://exercism.ioPractice modern C++ on a variety of problems and get

peer review and discussion of your solution.