Tag Archives: C++

C++ London Meetup: Type Punning and Counting Nanoseconds

September’s C++ London Meetup featured two talks: Type Punning by Timur Doumler and Counting Nanoseconds by David Gross of Optiver. Optiver were the generous sponsors of this event, hosted at SkillsMatter near Moorgate.

Counting Nanoseconds

Optiver are based in Amsterdam and operate in the High-Frequency Trading sphere. Naturally, they need code to be fast in order to take trades more quickly than their competitors, but the benefits of fast code also extend to minimising energy costs in data centres and extending battery life on portable devices for other applications. David Gross spoke about micro-benchmarking – boiling code down to very small numbers of instructions to aid comparisons and improve performance. The caveat was that it’s always vital to measure performance in production using real data as well as doing this offline, low-level analysis against potted test cases. David warning against relying on the high-resolution clock which can be problematic (may not be steady and may not have the resolution you need). He often uses Intel Time Stamp Counter (TSC), although that’s not the original intention of that metric.

Type Punning

Timur is fascinated by the ability to take an object and treat it as another type in C++. Yet, in many cases, this results in undefined behaviour. For example:

class Gizmo {
  public:
  virtual void print(){ std::cout << "Gizmo\n"; }
};
class Widget {
  public:
  virtual void print(){ std::cout << "Widget\n"; }
};
Gizmo g;
Widget* w = (Widget*)(&g);
w->print();

The behaviour of this code is undefined, because Widget and Gizmo are unrelated, although both have a virtual print function, so the virtual function table is the same. The standard says that you can’t call a method on a reinterpret-cast’d object – you can only cast it back to the actual type of the object. But on most compilers tried by Timur, the code runs and prints “Gizmo”. He referenced the CppCon 2018 talk, Undefined Behaviour is Not an Error.

Other examples concerned how to share memory across multiple data types, such as treating 4 bytes as either a char array or as a float. Even using a union can result in undefined behaviour, because only one member is ‘alive’ at a time. In order to write portable code, you must consider aliasing rules, object lifetime rules and alignment rules. In same cases, you can use C++17’s std::memcpy to ensure alignment (but only if the types are the same size and trivially copyable). std::bit_cast is coming with C++20. And in C++23, there’s a proposal for std::start_lifetime_as(char[]) to implicitly create objects, for example when reading from a buffer.

The video for this talk is available on SkillsCast.

Leave a comment

Filed under C++, C++ Code, Meetup, Programming

ACCU Meetup: Making Templates Easier, Roger Orr

Roger Orr gave this month’s ACCU presentation on Making Templates Easier in C++. He showed two techniques that people commonly use to tailor template implementations for specific types: Tag Dispatch and SFINAE (via enable_if).

With Tag Dispatch, you can switch to different implementations of a template function using traits classes based on one of the input parameter types (e.g. use std::iterator_traits to target a faster implementation for random access iterators). The downside is that you often have to duplicate code across the different implementations.

With SFINAE, you can use typedefs within a parameter type to disable particular overloads. E.g. STL containers have a ::value_type typedef, so you can use that to differentiate between collections and scalar inputs. The downside is that you sometimes have to add additional, defaulted template parameters to allow the compiler to distinguish between otherwise identical template definitions.

Roger then introduced constexpr if from C++17 and concepts from C++20.

The advantages of constexpr if are that it can be used both inside and outside templates and specialisations can be defined inline. Any code that would not compile can be put inside a constexpr if and will be discarded. This seems more straightforward than the recursive template solutions Roger showed earlier in the talk.

Concepts are intended to help define the requirements of a template in a way visible to the compiler as well as the developer. Reusing concept definitions should leave to a domain-specific language that helps within a project. Better still, use of a template parameter type that doesn’t satisfy concept requirements will generate a more helpful error message than if SFINAE were used to achieve the constraints.

The finale was an overview of the new SpaceShip operator, !

The video is now available on the SkillsMatter website.

Leave a comment

Filed under C++, Meetup, Programming

ACCU Meetup: Functional C++ (Phil Nash)

meetup-functional-cPhil Nash presented his ideas on functional C++ to a packed ACCU meeting a couple of weeks ago. He kindly provided the slides on his website.

For the uninitiated, the functional style is often quite a shock, but having written F# for some time, I’m in favour of “modelling computations as evaluations of expressions” as Phil presented it, or the declarative style as it’s often described. I wrote about Higher-Order Functions in C++ recently and Phil touched on that as well.

One of the highlights of the talk was the section on persistent data structures, which share as much of the previous state as possible whenever additional elements are added. For example, an associative binary tree could have a new element added, but retain links to the bulk of the original tree. There are challenges to stay balanced, but often the benefits can be worth it (e.g. a red-black, persistent tree that’s thread-safe because all the data is immutable). Phil also presented a Trie hybrid with hashing – a persistent tree structure, with performance similar to unordered_map, for which the hashing ensures no re-balancing is required.

The finale was a demonstration of pipelining for C++, based on std::optional (available from C++17). The recommendation was to watch Eric Niebler’s Ranges talk from CppCon 2015 for more details.

Leave a comment

Filed under C++, Meetup

Stateful Lambdas (Jason Turner)

I just watched Jason Turner’s latest C++ Weekly video, where he uses C++14 generalised lambda capture to implement the fibonacci sequence:

screen-shot-2016-11-15-at-13-54-29

This is very cool – I hadn’t seen Fibonacci done this way before. I was interested in std::exchange too, introduced in C++14. As used here, std::exchange replaces the existing value of j with a new value and returns the original value, which is assigned to i. So this idiom allows you to update a value and store the previous value, all in a single expression.

Even better, Jason shows that this whole program is calculated at compile time in Clang – very impressive.

Leave a comment

Filed under C++

Video: Writing good C++14 with Guideline Support Library (GSL), Bjarne Stroustrup

ISOCpp.org re-advertised the Channel9 videos from last year’s CppCon, so I thought I’d watch a couple. I started with Writing Good C++14. The slides are available here.

Stroustrup’s aim is to provide guidelines for writing simpler, cleaner C++ – then use this to spread the word of how Modern C++ can be so much better than archaic C++ idioms that have been superseded by new techniques.

But how to do it, because coding guidelines are frequently ignored or wrong. Telling what not to do is not enough – you need to do more than prohibit use of certain language features. Instead, build a set of what you should do – comprehensive, browsable, teachable guidelines.

High-level rules: philosophical approach to coding. And low-level rules: more specific, tangible rules that can be checked using tools (at least in the future) – each rule must have a rationale and an example as well as alternatives/exceptions/enforcement. And Guideline Support Library (GSL) for useful abstractions over messy/dangerous features – e.g. not_null, owner, array_view.

Result could be: productivity doubled (like a great programmer working on a modern codebase); less debugging by eliminating whole classes of errors – resource leaks, dangling pointers.

For example, dealing with range checking:

// Before
void f( int* p, int n ) // this is Stroustrup's least favourite interface!
{
    p[7] = 9;
    for ( int i = 0; i < n; ++i ) p[i] = 7;
}

// Guideline - better
void f( array_view<int> a)
{
    a[7] = 9; // checkable against a.size() e.g. in debug mode
    for (int x : a ) a = 7;
}

Example – dealing with null pointers:

// Before
void f( char* p )
{
    if ( p == nullptr ) // is it necessary to check every time?
    {
    }
}

// Guideline - better
void f( not_null<char*> p )
{
    // no longer needs to check, not_null<> cannot hold nullptr.
}

This looks pretty interesting – there’s a VS2015 plugin to run the GSL tools too. This featured in the follow-up presentation by Herb Sutter:
Screen Shot 2016-08-19 at 16.52.11

Leave a comment

Filed under C++, Programming, Video

C++17 News

Herb Sutter blogged about the Oulo ISO C++ meeting. There’s a link to an interview he did for the excellent CppCast podcast and also to a reddit post on features approved at the meeting.
CppCast

As Herb called out in the interview, I think the following two features will be widely used:
Structured Bindings
This is interesting because I’ve been using the std::tie syntax for a while, despite the clumsiness when you need to introduce new variables to take the return types (leaving them uninitialised until assignment). The proposal above avoids that problem.

tuple<T1,T2,T3> f(/*...*/) { /*...*/ return {a,b,c}; }

// BEFORE
T1 x;
T2 y;
T3 z;
std::tie( x, y, z ) = f();

// AFTER
auto [x,y,z] = f(); // x has type T1, y has type T2, z has type T3

Initialisation clause for if and switch
This proposal makes if/switch more consistent with for loops that allow separate initialisation/increment clauses as well as a condition. So now you can initialise a variable separately from the if condition, which also allows you to limit the scope of that variable.

// BEFORE
status_code c = bar();     
if (c != SUCCESS) 
{       
    return c;     
}

// AFTER
if (status_code c = bar(); c != SUCCESS) 
{     
  return c;   
}

Leave a comment

Filed under C++, Programming

Tech Book: Effective Modern C++, Scott Meyers

EffectiveModernC++When Scott Meyers announced his retirement from C++ duties, I thought I’d get a copy of his latest book. There’s plenty in it to interest even seasoned C++ developers – as always, Scott’s insight and in-depth examples are worth studying. I’ve tried out most of the C++11 features, but still learnt a lot working through this book.

Uniform Initialisation and Auto
Meyers points out that compared to parentheses or just plain “=”, braced initialisation can be used in the most contexts, avoids his famous “C++’s most vexing parse”, and will issue compiler errors if narrowing occurs. However, for types that can take a std::initialiser_list in their constructor, the compiler is required to favour std::initialiser_list over any other interpretation. That’s a deterrent to use of braced initialisation with types that have a std::initializer_list constructor – and also precludes using auto with braced initialisation.

auto x = { 4 }; // type of x is inferred to be std::initializer_list&lt;int&gt;!

How to use the new “= delete” idiom
Meyers recommends declaring deleted methods as public to get better error messages from compilers that check for accessibility before deleted status. He also points out that you can declare non-member functions as deleted (I’d only seen examples of copy-constructor/copy-assignment operator as deleted before).

Use of noexcept on move operations
This one is a classic example of a combination of language features having an unexpected effect. std::vector::push_back offers the strong exception guarantee. It can achieve this using any copy constructor and being sure not to change the original contents of the vector until any new elements or copies have been constructed. Hence, move constructors are only preferred if it is exception-safe to do so – which means they must be marked as noexcept (and if that isn’t appropriate, you just won’t get move semantics pushing instances of your type into a std::vector).

Recursion with constexpr
Having toyed with template meta-programming in the past, this use of constexpr appeals to me:

constexpr int pow( int b, int exp ) noexcept
{
    return (exp == 0 ? 1 : b * pow( b, exp-1 ));
}
constexpr auto eight = pow( 2, 3 );

void testConstExpr()
{
    std::cout &lt;&lt; &quot;2^3 = &quot; &lt;&lt; eight &lt;&lt; &quot;\n&quot;;
}

It’s much more succinct than the equivalent TMP version, and still performs the calculation at compile time.

Summary
In the past, I’ve recommended Effective C++ for developers who have little experience of the language and wish to improve their skills. I think this book is a bit too advanced for that, particularly given the chapters on template type deduction and decltype being in the first part of the book! So read this book if you’ve got a few years’ experience of C++ already, but look at Effective C++ (3rd Edition) to improve on the basics.

Four stars

Leave a comment

Filed under C++, C++ Code, Programming, Tech Book

C++14 Language Extensions

Whilst reading Scott Meyers’ Effective Modern C++, I was looking for some clarification on ‘generalised lambda capture’ and came across this C++ 14 feature list. It was interesting to compare to the list of expected features that Bjarne Stroustrup presented at the ACCU 2013 conference – he described all of the following, which made it into C++14:

  • Generalised return type deduction for normal functions, not just lambdas
  • Generic (polymorphic) lambdas
  • Generalised constexpr functions (listed as Extended constexpt on the feature list)
  • Binary Literals
  • Digit Separators
  • Deprecated Attribute

However, this one appears not to have made the cut:

  • Runtime-sized arrays

This would be a great new feature and I blogged about it at the time – but it appears the work has stalled.

Leave a comment

Filed under C++, Programming

Tech Book: A Tour of C++, Bjarne Stroustrup

A Tour of C++ This recent book was recommended by Herb Sutter at CppCon as a slim summary of all that C++ developers should be expected to know. It’s a good read, sprinkled liberally with example code to illustrate the techniques that make up modern C++. Having originally learn C++98, then spent a lot of time reading and trying our C++11 techniques, it’s interesting to see how the language looks when presented as a whole. Also, the book covers some C++14 additions.

The points I particularly found interesting were:

  • override – use this to mark virtual methods that are declared in the base class and have an implementation in the derived class (avoids declaring a new virtual method if the signature is wrong)
  • explicit – single argument constructors should by default be marked as explicit to avoid unexpected implicit conversions, unless there’s a reason not to
  • delete – when defining a base class, it’s good practice to ‘delete’ the default copy and move operations, given that the default implementations will not know how to handle derived class members
  • regex – the book covers the standard library as well as the language. A welcome addition is std::regex, and the chapter in this book is an excellent introduction
  • vector initialisation – uniform initialisation of vectors of a struct can still use initialiser lists, even if the struct members have different types e.g. string/int
  • vector::at – this method returns the same value as operator[] (subscript), but performs bounds-checking, which doesn’t happen with operator[]

Four Stars

Leave a comment

Filed under C++, Tech Book

Bjarne Stroustrup: Five Popular Myths about C++

Catching up on my C++ reading, I read through Bjarne Stroustrup’s 5 Popular Myths about C++ and why he believes they are wrong:

  1. To understand C++, you must first learn C
  2. C++ is an Object-Oriented Language
  3. For reliable software, you need Garbage Collection
  4. For efficiency, you must write low-level code
  5. C++ is for large, complicated, programs only

Worth reading for the surprising amount of hostility he reports to these arguments, which on the face of it I thought were pretty reasonable.

The comments prove yet again that the “Myths” paper was needed. People keep repeating the old hairy rationalizations. Unfortunately, many programmers don’t read long papers and dismiss short ones for being incomplete. The unwillingness of many programmers to read a long paper was the reason I released this paper in three separate parts.

Leave a comment

Filed under C++, Programming