Category Archives: C++

C++: std::make_array (N4315)

I read in May 2015’s CVU that there’s a proposal for std::make_array, a utility method in the same family as std::make_tuple and std::make_pair.

This would be a useful shorthand:

// Existing usage
std::array<double, 3> a = { 1.1, 2.2, 3.3 };

// Proposed usage
auto a = std::make_array( 1.1, 2.2, 3.3 };

The obvious benefit is that you would no longer need to specify the number of elements in the array, making the code more maintainable.

Leave a comment

Filed under C++, C++ Code

Video: Herb Sutter Back to the Basics at Cpp Con 2014

Herb Sutter’s Back to the Basics video is hardly an introduction to C++ as the name suggests. Rather, it clarifies his default choices when faced with some basic tasks like parameter passing, in the light of modern C++ techniques.

Don’t pass owning choices down the call stack – use non-owning raw pointers and references when you don’t need ownership transfer down the call stack, e.g. when callee parameter’s lifetime entirely nested within the called method. If the called method doesn’t participate in ownership, it should be agnostic to the lifetime of the object, whether on the stack, the heap, global, shared_ptr or unique_ptr.
image

Another reason to use auto is performance – it guarantees no implicit conversion because there’s no explicit declared type.
20150326-120815.jpg

Reviewing parameter passing choices, established rules of thumb still apply, they just got better.
20150326-121118.jpg
This is especially true for pass-by-value, which experts considered to be the new default choice for a while for moveable types, but is now only recommended for constructors that wish to retain a copy.

There was a bonus slide on returning multiple values using std::tie, which I’ve been doing for a while.
image

Finally, it seems that there’s a new term for Universal References – “Forwarding References”. I agree that this states the intention of T&& parameters better that Scott Meyer’s original name, although my eBook of Effective Modern C++ still uses the old name.

Leave a comment

Filed under C++, Programming, Video

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

Overload magazine: Order Notation in Practice

Overload 124Roger Orr wrote an excellent article for Overload about complexity measurement. It’s amazing how many candidate for programming roles in general, and C++ roles in particular, aren’t comfortable with order notation. This introduction should be a must read before interviewing!

Leave a comment

Filed under C++, Programming

How to speed up your C++ build

I’ve been working on a software library for some time and have seen it grow to include a large number of types. This has gradually increased the time needed to build the library – in fact, to build the whole package in our CI system recently hit an hour. At that point, I needed to take action to bring the build time back to a reasonable level.

  • Increase the number of cores on the build machine
  • Reduce the number of header includes per source file
  • Configure pre-compiled headers on the largest projects

Build

The graph above shows the improvements with each step. Doubling the number of cores on the build machine halved the build time because much of the time is spent compiling .cpp files which can be done in parallel.

Reducing the number of header inclusions also had a big effect. Initially, I’d taken the approach that all headers could be included stand-alone, and they would include their own dependencies. For this large project, though, that turned out to be expensive – so instead, I produced a single header that included all the others in the right order. Although that also has drawbacks (like, any change to any of those headers forces all the project files to be re-built), it’s reasonable for the workflow involved in this area of work.

Finally, turning on pre-compiled headers had a really noticeable improvement – particularly in building individual projects within the package (which many of our developers will be doing). From what I’ve read on MSDN, the previous step was a pre-requisite – it’s recommended to have .cpp files include the same framework header files in the same order.

Leave a comment

Filed under C++, Programming

C++: reasons to return void and/or return early

I was recently refactoring some code, leaving a function in which the most natural thing was to return a call to a void function. The code structure was like this simplified example, where I wanted to return early from a nested if statement, but it felt clumsy to put bar() and return on separate lines:

void bar()
{
    printf( "bar\n" );
}

void foo( int a, double b )
{
    if ( a > 0 )
    {
        double c = a * b;
        if ( c > 0 && c > a )
        {
            return bar();
        }
    }

    printf( "foo\n" );
}

I was surprised that this worked, because I half expected the compiler to do something sinister like optimise out the call to bar(), given that it returns void and only executes useful code via side-effects.

This post asks the same question, but it seems that this is supported in C++ and can be useful for template functions that return void.

Some readers may take issue with the early return in the code above. I admit I used to follow the mantra of maintaining a single return point in any function (except perhaps an early return after checking pre-conditions on parameters). However, the modern C++ take on this is that early returns are recommended and may lead to faster code. Herb Sutter has this to say:

allowing the function itself to return early when it knows it’s done is perfectly fine and fully under the function’s control. To put the final nail in the coffin, note that “single exit” has always been a fiction in any language that has exceptions, because you can get an early exceptional return from any point where you call something that could throw an exception

.

Leave a comment

Filed under C++

Video: Herb Sutter on Visual Studio cross platform development

Exciting times for C++, you can now target multiple compilers and platforms from a single IDE, Visual Studio.

IMG_3544.PNG

IMG_3545.PNG

Leave a comment

Filed under C++, Programming, Video

Bruce Dawson – crash investigator

Another great post from Bruce Dawson,
with some valuable tips to check compiler flags in Visual Studio to aid debugging of an entire class of crashes.

/GS, /NXCOMPAT, /DYNAMICBASE, /analyze and all its associated labors – plus actually fixing the bug – took a lot of time, but it was definitely worth it. Most of these changes were trivial and had huge payoffs. Running /analyze was by far the biggest task but, like other smart programmers, I am convinced that it was invaluable. Entire classes of bugs – serious crashing bugs and crazy logic errors – that use to show up quite frequently are now entirely extinct. It is not often that you get to entirely eradicate dozens of types of bugs and doing this definitely increased developer productivity and product reliability.

I’ll certainly check these are set for the projects that I own.

Leave a comment

Filed under C++, Programming

How to achieve pattern matching in C++ using boost::regex

Suppose you are parsing text input and need to handle the string representation of a field that could have several formats. In that case, using regular expressions is appealing because you can try a number of patterns sequentially (taking the most likely first) and exit when you get a match.

When I tried to do this in C++, I found it hard to find an easy example to follow. Here’s the way I’ve been doing it, based on a simple example to parse a length that could be in any of several units of measure:

    #include <boost/algorithm/string_regex.hpp>

    void parse( const std::string& candidate )
    {
        boost::smatch value;

        if ( boost::regex_search( candidate, value, boost::regex( "(.*)ft(.*)in" )) )
        {
            auto feet = atol( value[1].str().c_str() );
            auto inches = atof( value[2].str().c_str() );
            std::cout << "Matched " << feet << " feet and " << inches << " inches\n";
        }

        if ( boost::regex_search( candidate, value, boost::regex( "(.*)m(.*)cm" )) )
        {
            auto metres = atol( value[1].str().c_str() );
            auto centimetres = atof( value[2].str().c_str() );
            std::cout << "Matched " << metres << " metres and " << centimetres << " centimetres\n";
        }

        if ( boost::regex_search( candidate, value, boost::regex( "([0-9]+)mm" )) )
        {
            auto millimetres = atol( value[1].str().c_str() );
            std::cout << "Matched " << millimetres << " millimetres\n";
        }

        throw std::runtime_error( (boost::format( "Failed to match candidate '%1%' with ft/in, m/cm or mm" ) % candidate).str() );
    }

This only uses a fraction of what can be done with regex – the point is to show how to use boost::regex. One gotcha is that, as per the code above, the string matches that are written into value are indexed from 1 – for some reason, the zero’th index accesses the whole candidate expression. Another gotcha is that boost::regex is one of the few boost libraries that isn’t just implemented using templates in a header file, so you also have to add the appropriate .lib into the linker inputs.

1 Comment

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