Tag Archives: C++14

Modern C++ in Embedded Systems

I was thinking about C++ for embedded environments recently and wondered how much of today’s Modern C++ was recommended for use. I found an excellent article by Dominic Herity on the subject:

  1. Modern C++ in Embedded Systems – part 1
  2. Modern C++ in Embedded Systems – part 2

Even better, Dominic linked to some presentation materials Scott has published electronically on the subject. I’ve long been a fan of Scott’s writing and wasn’t aware of this electronic book, so I’m reading that next.

Leave a comment

Filed under C++, Programming, Tech Book

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

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

C++: Resumable functions, Async and Await

Interesting post from Jens Weller on the new concurrency features in C++ 11 and C++ 14. He gives examples of code written using standard library async, futures and “.then()” with lamdbas, compared to the simplicity of expressing the same functionality with the proposed resumable functions (that is, resumable and await as language keywords).

Whilst resumable and await won’t be part of the language until at least C++17, Weller points out that Microsoft may put implementations into Visual Studio well before that. Here’s the paper, N3722.

Leave a comment

Filed under C++, Programming

Runtime-sized arrays v std::dynarray in C++ 14

Interesting question on StackOverflow regarding the differences between the proposals in C++14 for std::dynarray and runtime-sized arrays.

Leave a comment

Filed under C++, Programming

Guru of the Week restarting from Item 1

Herb Sutter is reviewing his Guru of the Week series from item one, in the light of features in C++11 and C++14. This will form the backbone of a new issue of Exceptional C++.

Leave a comment

Filed under C++, Programming

C++14: Runtime-sized arrays

More details on the ISO C++ blog about runtime-sized arrays in C++14.

N3639 proposes to add local runtime-sized arrays with automatic storage duration to C++, for example:

void f(std::size_t n)
{
int a[n];
for (std::size_t i = 0; i < n; ++i)
{
a[i] = 2*i;
}
std::sort(a, a+n);
}

Traditionally, the array bound ā€œnā€ had to be a constant expression.

2 Comments

Filed under C++, Programming

ISO C++ Spring 2013 Report

Herb Sutter has posted his trip report from the ISO C++ Spring 2013 meeting in Bristol.

The post includes details on features to be included in C++14, including:

  • std::make_unique – never use “new” again
  • Generic lambdas – allow auto for type name in lambdas
  • Dynamic arrays – stack-based arrays can take size parameter at runtime
  • std::optional – for variables that are ‘not set’ (like F# option)
  • Concepts lite – constraints for templates

Leave a comment

Filed under C++, Programming