Technology

CppCon 2019: Modern C++ debugging tools

Greg Law

gdb

  • ptrace()
  • signals ony reach the tracee via PTRACE_COUNT
  • breakpoints and single step are SIGTRAPs
  • ^C is SIGINT
  • modify instruction causes SIGTRAP

DWARF

g++ -g3??? ; helps make inline functions not look inline; macros

  • “Optomized out” really means it’s just later
  • readelf —dump-debug
  • can actually track registers while live
  • Call frame analysys
  • Catch throw or catch
  • Libthreddb

address Sanitizer

Malloc and free are intercepted. Shadow memory keeps track

Replay

Record and replay nondeterministic steps. Just Re execute to get to current point

Static analysis

What’s The best way for a c++ programmer to make money? Inheritance

Synopsis

Standard
Technology

CppCon 2019: Naming is Hard: Let’s do Better

Kate Gregory

gregcons.com/kateblog

Naming things

  • It matters
  • It’s a learned skill

Not Naming conventions

  • camelCase, snake_case, PascalCase ….

Names carry meaning

  • expire date vs end date
  • is a date or datetime
  • It matters everywhere
  • Bad names confuse
  • Giving something the correct name may happen long after it’s first written

Naming requires empathy

  • sort/partial_sort/partial_sort_copy
  • top_n() is better name

Consitency

  • Names exist outside of your code
    • Headings n reports
    • Emails
  • Alaows call things by their proper names, everywhere
  • Don’t use same words for different things
  • Don’t accept similar English words in conversation
  • Don’t invent business works
  • Avoid pre/post and other “dependent” names
    • Unless the business uses them
  • Prefer single English words like “Save” or “Location” vs UpdateConfigFile and StorageCoOrdinates
  • Don’t mimsmatch
    • begin goes with end, …
  • Functions are verbs
  • Helper verbs: isEmpty() less ambigrous then empty()
  • isShippable() vs canShip() vs getShipStatus()
    • avoid the “-able”
  • Tools matter
    • alphabetical lists
  • Classes are Nons
    • Anything ending in “er (et al) is suspect without a noun
  • Adjectives are your friend
    • FullName not Name
  • Avoid encoding type
    • exceoptions: Date, asX
  • Maybe avoid leaking enums? e.g. instead of getStatus() == Application::OK maybe isApproved()
  • Don’t abbreviate
  • templates:
    • One? T is ok
    • Two: make meaningful
  • When to name things? When you know what it is
    • Sometimes before you even write the code
    • Never miss an opportunity to fix a name
    • Sometimes when code chnags the names need to change

Better naming

  • Care about the code you write and the people who will read it
  • Think about the purposes names server
  • Don’t be paralyzed
    • Fix it later
  • Demand good names
  • When you learn what something is, fix its name
Standard
Technology

CppCon 2019: Better code: relationships

Sean Parent

  • Let’s rotate (cppcon six years ago); meme?
  • – Goal: No contradictions
  • A novice sees only the chessman; an amateur sees the board; a master sees the game

Entity notation

  • Witnessed Relationships: a relationship represented by an object
    • copyable and equality comparable
  • When an object is copied or moved any witnessed relationship is either maintained, severed, or invalidated
  • When an object is destructed any witnessed relationship is either severed, or invalidated

Safety

  • std::move()

    is an unsafe operation

C++20

  • One new feature: concepts (joke about contracts)
  • Hoare Logic (paper from 1969, C.A.R Hoare)

Equality

Applying “Design by Contract”

Contracts

  • Preconditions (require)
  • Postconditions
  • Invariants

Concepts

A compile time constraint to select an appropriate operation

Contracts assert at runtime if an an operations

A runtime constraint to select an appropriate operation is know a pattern matching

No Raw Loops

The Game

  • Architecture is the art and practice of designing and constructing structures

Timer example

Registry

Container support these:

  • Add an object and obtain receipt
  • Use receipt to retrieve the object
  • iterate

Russian Coat Check Algorithm

  • Receipts are ordered
    • Coats always appended with stub
    • Binary search to retrieve coat
      • when more than half the slot are empty; compact the coats
  • Coats are always ordered receipt stubs
  • Coats ordered by insertion

Double entry bookkeeping

  • Every transaction twice
  • 5 standard accounts: Asses, Capital, Liabilities, Revenues, and Expenses
  • This ensure the mechanical process of entering a transaction is done in two ways

Contradictions

  • unit tests expose contradictions

No Raw Synchronization Primitives

Use strong preconditions to move the issue to the caller

Setting a property

  • Code is redundant
  • – Different aspects of the same code
    • value is a*b when a changes
    • other_value is a*b when b changes
    • asking for troubles
  • Different, mutually exclusive relationships with non-local control
  • Implied last in wins relationship
  • An incidental algorithm; property convert to the correct value
  • property is not a simple property but a stream, trigger, or latch
  • or it’s just wrong

No Raw Pointers

https://sean-parent.stlab.cc for talks

Standard
Technology

CppCon 2019: Time Travel: Gradual Typing in C++

Hyrum Wright

C++ is a dynamically typed language

example with sso_string and union

If somebody can (ab)use your API, they will

Types Encode constraints

int timeout;
int number_of_pumpkins = 6*timeout;

better:

void set_deadline (absl::Duration deadline);


See “Time Programming Funamentals” by Greg Miller

Abseil Time API

  • Valid invalid operations: Duration + Duration gives Duration;
Duration + Time gives Time;
Time + Time is invalid, etc

Gradual Typing

  • python: adds annotation

Goals

  • Automated (almost) everything
  • Keep code buildable (each multiple steps)
  • Keep code readable
  • Eventually converge at a fixed point

Things that don’t work

  • Monolithic changes
  • Variable type
    • Most integers don’t represent time
  • Variable name
    • What does timeout_seconds actually mean?
  • Comments super unreliable

Types of transformations

  • Expression
    • Simplification
    • Comparison
    • Addition and Subtraction
    • Distribution
  • Variable
    • Local, global, class members
  • Inter-function
    • Parame and value

Expression: Simplification

  • Makes matching easier
  • clang-tidy code for matcher
  • code for fixer

Expresion: Comparison

Inter-function return values

Seeding Type Information

  • Identify high value targets

Reactions

  • You added a bug … oh
  • Thanks
  • (crickets)

Other applications

  • Converting to std::string_view
  • Ownership deduction (i.e. std::unique_ptr)

GitHub.com/llvm-mirror/clang-tools-extra/tree/master/clang-tidy/abseil

Questions

  • How to justify? “We should be able to change our software”
Standard
Technology

CppCon 2019: CppChat Live

John Kalb, Andrei; Herb Sutter; Phil Nash

Talking about giving a presentation

  • Recommending session
  • Giving a talk is a performance.
  • Andrei: treats each talk as different at different event. Re-does slides

Review of Andrei’s keynote

  • sort()

    algorithm needs to make many decision: attributes need to be introspected/reflect. E.g. cost of comparison; cost of move; etc

  • metaclasses are an example of this (Herb Sutter).
  • “Modules help with new features? e.g. exceptions”
  • “The dawn of a new error” by Phil Nash
  • Swift assumes out of memory is not recoverable. “C++ aspires to handle out-of-memory”
  • Looking at error handling is a great way to evaluate a language
  • Andrei:
    static_if

    is a fundamental building block just like

    if
Standard
Technology

CppCon 2019:From STL to Ranges

Jeff Garland

Intro

  • The beginning of the end – for begin and end

Basics

std::sort(a.begin(), a.end())

Instead:

ranges::sort(a);

Example with find_if

the ranges way: filter_view

for (int i : rng::filter_view (a, is_six)) { std::cout << i << “ “; }

Tristan Brindel NanoRange

Godbolt

  • supports several
  • range: something that can be iterator over
  • range algo: algorithm that takes range
  • view: lazy range thats cheap top copy
  • ranger adapter: turn range into a view

mechanics

  • 3 new names ranges, ranges::views, views = ranges::views

Why new namespaces

  • behavior and guaranteed of some algorithms are changed

What’s a range

  • iterator pair is simplest
  • sentinel and iterator can be different types
  • ranges can be infinite
  • any container with begin()/end() can be used in a range

Views are ranged with lazy evaluation

  • non-owning of elements
  • all methods
    O(1)

    for copy and assignment

range adaptors -> views from ranges

  • pipeline syntax

filter_view adaptor

for (int i = range_filter_view (vi, is_event))

No more for loops

Range Algorithm details

  • list of range algorithms

Projection parameters

  • provides first class filtering predicate
  • comes from the Adobe Source Libraries (ASL)

ranges::sort(vistuff, std::less<>{}, [](auto const &i) {return i.value;})

Views and View Adaptor details

How do ranges perform

  • Compile time: no noticeable difference
  • runtime: nothing expected over stl algorithms

Resources

wg21.link/n4810

Standard
Technology

CppCon 2019:Dawn of a new Error

Phil Nash

Exceptions

P0709 R2 Zero-overhead deterministic exceptions (static exceptions)

Swift has best error handler

Exploding return types

p03w3R7 std::expected

p0798R4 Monadic operations for std::optional

What is std::error

p1028R1

GitHub.com/ned14/status-code

error code always represent an error

p1029R1 [[move relocates]

p1144 object relocation in terms of move plus destroy

With compiler optimizations no extra overhead compared to regular return

error_code fits in two registers

auto result = try add_one (divide (42, parse_int(input));

levelofindirection.com/refs/dawn.html

boost::outcome

Question

  • What is
    intptr_t

    ?

Standard
CppCon start
Fun, Technology

CppCon 2019: Some photos

CppCon moved to Denver, Colorado (technically Aurora, CO) just a few miles from Denver Airport. 1400 people attended from Sept 16-20 and a 150 talks over the 5 days. Additionally, there were 1 and 2 day training classes the weekends before and after the conference.

The Gaylord Rocky Mountain Resort hosted CppCon. It’s a huge place that’s very conference oriented though there are some nice pools and rec areas. You are pretty isolated so plan on eating at the nice but overpriced restaurants.

Standard
Technology

CppCon 2019: Getting Allocators out of Our Way

Alisdair Meredith and Pablo Halpern

Allocators are great

std::pmr::monotoic_buffer_resource src(buffer, sizeof (buffer);
pmr::set. uniq(&src);

What if we could reduce the cost

goal: reduce cost of developign an allocator aware

What’s our problem?

Allocators bloat class interfaces

Performance in practice

  • Memory hiearchy: Cache; main, virtual
  • objects used together should be together

C++ allocatros

allocator_traits simplify allocators; mostly for users. Containers now have problems in their face

What about nested containers

  • In a vector<string> vector has one and each string potentiallly different allocator
  • scoped allocator model: container passes allocator into each item. Solves memory diffisuion
  • scoped_allocator_adapter
  • Allocator template policies interfere with vocabulary types

C++17: PMR: a simpler allocator model

  • Non-template std::pmr::memoryresource
  • The wrapper
  • class memory_resource
  • polomorphic_allocator
  • polymorphic_allocator<byte>
    • “One true” allocator vocabulary type
    • Only a template to be compatible for C++11
  • std::pmr::new_delete_resource()
    • Uses new/delete
    • always availabel
    • thread safe
  • unsynchronized_pool_resource
    • Pools of similar sized objects
    • good for dynamic data strucures
    • Single-threaded
    • avoids concurrency lock overhead
  • monootonic_buffer_resource
    • Ultra fast; single threaded, contiguous
    • for containers that grow monotonically
  • test resource
    • GitHub bloomberg/p1160

How to use allocators

class Student {
  pmr::string d_name;
pmr::string d_email
pmr::vector<int d_grades;

using allocator_type = pmr::polymovic_allocator<>; // Important

}

  • Overload each constructor having default_arguments
  • Variadic argument lists: allocator goes at the beginning

Rewriting std::unordered_map to use pmr allocators

  • Example with copying constructors. Lots of duplicated code

What about a language solution

  • Build on a strong foundation built up to C++17

HashMap<int,int> x {} using myAllocator;

  • using myAllocator

Bloomberg

  • Bloomberg vision 2020
Standard