Tag Archives: C++

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