You are on page 1of 15

The Mechanism of Art C and C++17.

© 2019 Marcel Deberi. All rights reserved.


EDITION 1 REVISION 2
These excerpts are from the near 200 page book based on a tutorial course
covering C to C++17. These excerpted pages may be redistributed to any
legitimate online educational distribution channels or printed/referenced
provided the content as is remains unaltered in anyway. The complete book may
be purchased via paypal from a link on my website www.aexa.uk or by sending
me an email marcel@aexa.uk or mldbmail@gmail.com © 2019 Marcel Deberi.
All rights reserved 2019.

BOOK EXCERPT - FOREWORD

The Mechanism of Art C and C++17


Marcel Deberi © 2019 All rights reserved
edition 1 revision 2

FOREWORD
C & C++ Re-lit.
C is important because it deliberately adopted a less is more approach believing
that the intellect of the programmer was the final authority on program design.
This is not to say people are incapable of making mistakes (they will do that in
any Computer language anyway). In many ways at this simple level the
program becomes its own *Contract* with the system in that taking a simple
approach it becomes *self documenting* this entire idea was encapsulated in 'C'
programming circles with the "Trust the Code" philosophy (and not the
comments). Furthermore it was a language that was designed with a particular
job in mind, much like Fortran for the Physicists or Algol/K for the Symbolists,
then C was designed to facilitate ease of programming a system close to the
actual hardware (a reality of making any computing machinery work) and has
features that make that easy in the same way that Fortran allows some
Mathematical Physics easier to do. Some people might refer to C as a system
assembler on steroids and it certainly has something of that about it, that is,
having very little proscription on how to interact with machine hardware.

In modern times it has gained more traction with NVIDIA's adoption of C and
indeed C++ as their main development language for their CUDA HPC paradigm
and the many variants that have followed on such as OpenCL.

C++

C++ as originally conceived was a C with objects. It has had a difficult


development. Originally intended to enable object modelling as a graft to
standard C. In fact the first C++ compiler Cfront was simply a preprocessing
stage generating a C program that a C compiler could compile. This early
compromise which lead to philosophical and practical limitations on its less
than perfect object model, trying to sort out its own development path different
to Smalltalk, then the canonical standard for Object Orientation, people
struggling with the integrated dimensionality and apparent dichotomy of a
sophisticated object modelling language (C++) living alongside an efficient
machine language (C) opened C++ up for a lot of justifiable criticism. At this
stage having philosophically and functionally stalled, people looked elsewhere.

Now with the recent post CUDA/GPU interest C++ has gained a resurgence. A
lot of new work has ironed out the problems of old and made C++ in modern
times (2015-2020) a serious proposition as an extremely powerful and
competent language. It has stayed true to its compile to true machine code
approach which in the times of C#, Java and PHP the traditional de-facto 'brand-
new for the internet' languages make C/C++ as the language with an
unwavering record of true scalability. From very small microcontroller projects
to the enterprise cloud and I draw attention to facebook having to back out from
their reliance on native PHP as proof.

Unfortunately a lot of C++ reading material can be both Prosaic (too much
verbage taking an age to make a point) and Mosaic (one fractured piece that's
lost in translation among a giant jigsaw of a language). These styles are
unfortunately probably a requirement of modern book publishers. My book, as
you will see, is written for professional developers and not professional book
readers.

This book is deliberately kept short at under 200 pages. As long established in
software development I have seen programming language books go from 250
pages to 1200 pages long. If you already know how to write what is considered
good code because you've been doing that in industry for a few years then you
just need to know the ins and outs of how to do the same using modern C++.
Uniquely (at 200 pages) this book attempts to take you quickly and purposely
through C and C++17 avoiding so much of the drek you are forced to wade
through in other books. This approach also makes the book ideal for anyone
setting out to learn the language.

Once you have gone through this book you should feel very confident and
quickly get to doing any C++ task. At this stage I would quickly move to doing
some C++ developments. If you are a student then set yourself a few serious
model developments. If for example you are learning to speak a foreign
language write a project you think will help you with that, and avoid a
composite solution ex. storing a library of words and translations in sql. That
may be a better way to do it for real but you will learn more about C++ if you
simply keep to a 100% C++ solution.

Other advice I would give is to avoid C++ stackexchange and encourage you
instead to break down the problem you are having into small steps to help you
think through the situation. I would also try and avoid books that are list based.
A list is easy to write and as you know at least very difficult to remember
notwithstanding the fact that a 400 page book of so called exemplar lists whose
real purpose may be not much more than to make a few people look smarter
than the rest of us on a subject that really is as trivial as C++.

Finally, I really would recommend the books written by the language's creator,
Bjarne Stroustrup. His experience of decades of language design for C++ is a
treasure of insight on all matters pertaining to C++. In particular "The Design of
the C++ programming language" and before you read that, as an excellent
introduction a short paper on the History of C++, both by Bjarne Stroustrup. A
man that has stayed with C++ and worked through its problematic development
as opposed to certain others who create one disaster of a language and are
rewarded by being allowed to create more.

About Me

Continually Involved in C since 1987 and C++ since 1995 largely for doing OS
design, Compiler design, extending microprocessor functionality in toolchains,
drivers for high end ($3000+) complex equipment and CUDA for some signal
processing tasks.
I am available for the more signficant roles in any of industrial research, design
or development. My website is www.aexa.uk my email is marcel@aexa.uk or
mldbmail@gmail.com

BOOK EXCERPT 1

C to C++17 Curriculum
A 5 day course (now available as a downloadable book) on C++ given by the
author and your instructor,

© copyright 2019, all rights reserved 2019 marcel deberi, marcel@aexa.uk

The examples in this course were compiled using

G++ 6.8.2 ( $g++ --version)

CLANG 6.0.1 ($clang++ --version)

GLIB 3 ($apt list –installed | grep libstdc++ or $objdump -x execbinfile )

• Introduction

• C++ as a procedural language


o For better or worse Stroustrup grafted C++
onto the procedural language C. There will be
C looking elements in your C++. An overview
and implications.

• Language design and OO as per C++


o What OO actually is in C++.

• The C++98 ANSI Std Core language


o The foundational elements of the language as
laid out primarily by Stroustrup and how to
use it.

• C++17 Language enhancements


o Rethinking the C++ framework including,

▪ New functionality,

▪ Streamlining old functionality etc.

• Concurrency in C++17
o How to overlay a threading model in an OO
language.

• Templates and Generic Programming


o What they are and how to apply template
techniques

• Parallel C++17
o Scaling STL for multicore.
• OO Design Patterns relevant to C++
o An overview of some popular C++ OO Design
Patterns

• Advanced C++17 topics

Some advanced C++ topics


BOOK EXCERPT 2

• C Pointers part II

Pointers are a big part of C. It is difficult to make a


comparison but they are probably as significant to
C in the same way as templates are significant to
C++.

The C pointer *mvar is a memory_address_TYPE.


Fewer and fewer languages have this intrinsic
concept and it is the reason why C is classed as a
systems programming language.

They are used double-duty to change values of


parameters passed to functions (C does not have
the variable-parameters offered by a routine
defined as a procedure and this is also one of the
reasons for its attribute of expressivity inherent in
the C language.

Pointers also get used to avoid having to copy large


datastructures onto program stack which at one
time was resource constrained and even today is
still also slow.

Since they are essentially mvar’s the compiler deals


with them in the quantity of actual machine words.
In doing this they were (not so much nowdays) a
source of nonportability since machine words in the
time C was created were not all created equally.

Yet another common problem was how to represent the


absence of any valid value for an mvar. A machine
word is just a collection of bits traditionally the width of
the databus. Ex. 8,16,32,64. Commonly an integer value
of 0 equated with the NULL macro definition was used.
This enabled tests such as if( !myptr ) meaning it’s not
pointing at anything useful. The problem with this is, if
myptr really is 0 and someone does myptr = 10 then,
that obviously causes a segv. Traditionally this is one
area that had to be resolved when porting C code from
one machine architecture to another. Again, portability
not so much of an issue anymore, everything runs on
Intel right?

For anyone learning C, pointers are always, usually the


stumbling block. The idea behind them itself is fairly
straight forward. It is perhaps the terseness
(overreliance) on elements of C’s syntax for their
manipulation that probably creates the confusion.

The next three tutorial examples hopefully will get C


pointers across in the right way and give confidence in
working with them. One final tip, if a C pointer
expression does look complicated break it down one
piece at a time like the terms of a complex math
equation.

BOOK EXCERPT 3

Language design & OO as per C++


• There are various models at use when
implementing an OO language. Knowing
what they are and which C++ uses is
important.
o Class/Object model
Classes are pre-defined and inform
how any object instantiated from the
class is defined. Ex. C++
o Prototype model
No Classes exist at all. Everything is
an object. Objects may have a special
link to other existing objects, their
prototype from which it inherits
features. Ex. Smalltalk, Clojure

• As well as this distinction for objects a


further refinement defines how the actual
actions or methods are expressed in the
program using either:
o Declarative style – A statement
oriented style were the
algorithm/actions are detailed
statement by statement ex. C, Modula+
o Imperative style – you specify the
algorithm/action to be taken by
specifying what is to happen and let
the language system work out how ex.
SQL, Prolog, Clojure
o Functional style – not fundamentally
anything to do with OO per se but may
be used in C++ where it represents a
higher (second) order function that in
turn applies a function to the
parameterised types. ex. C++, Clojure.
Functional programming may also be
described as pure or impure depending
on admitting other styles and allowing
functional side-effects. Miranda is
considered a pure functional language.

• Conclusion C++
Implements OO using a Class/Object
model where the actions are defined in a
Declarative style.

BOOK EXCERPT 4

• Perfect forwarding

The classic use case for perfect forwarding is to


change the behaviour of a function f such that it
continues to work as before while integrating new
behaviour and catering for being called with
different ‘classes’ of datatypes viz. lvalue, rvalue.
This is commonly referred to as a wrapper. In C
this could all be accomplished with a 1 line macro
testing for the ‘C’ variable size of the macro
argument and then conditionalizing the call to the
appropriate function. The only drawback with the
C version is the lack of type-checking for the
macro definition.
// C – the original f function is changed to _f or xf()
// depending on what you want to accomplish. (+/-) or -
// now we can link new functionality for f with a macro
// #define f( arg )\
// (sizeof( arg ) == sizeof( char* ) ? _f() : fnew() );
//
// usage: both will work
// f( &v ); f( v );
//

The C++ version is not all that different. Again it


depends on the very useful remove_reference type
trait.
//
// if we look up the definition for std::forward()
// we will see that
//
// input: parameters are t - the object to forward and
// it returns as
// output: static_cast<T&&>(t) - an rvalue
//

BOOK EXCERPT 5

• Dynamic memory management in C++


o C++ introduces two integral operators for
performing dynamic memory allocations.
These being new and delete.

o The reason for this was to allow object


instantiation of object types which will also
invoke the object’s ctor if the memory is
allocated. This avoids a call to allocate
memory for an object and a second call to
instantiate the object via its ctor
p = new T [ 10 ];

// 10 objects of object type T are allocated storage


and also 10 ctors are called

delete []p;

perhaps more common array allocations

int *intp = new int[ 10 ];

delete []intp;

• Automatic memory reclamation aka Garbage


Collection

o C++17 does not have any automatic Garbage


Collection.

▪ GC assumes that it can cleanup unused


memory without regard to any ordering
dependencies. (Ex. Eiffel does not have
dtors, Ex. basic dynamic arrays[]).

▪ C++ with Inheritance and Dtors requires


and depends on an implicit ordering.

o C++17 does offer improved memory


reclamation with the new smart pointers,
unique,shared and weak.

o C++17 also always had a technique called


RAII which guarantees dtors being invoked
even when exceptions are in-flight.

o Languages with GC (Eiffel) do not have dtor


methods in the way C++ has.

o Current collection algorithms either implement


reference counting or mark-and-sweep
techniques.

o Current techniques do introduce a significant


latency to C++ programs and a non-
determinism as to when GC will happen

▪ Worst-case : at program exit which is also


when any OS would do the same thing

▪ Realtimes systems therefore will avoid


Garbage Collected languages.
o A proposal (n3210) based on the Boehme
collector was made for C++11 but technical
issues were not resolved

▪ Thread safety.

▪ Third-party libraries.

You might also like