Tag Archives: C++11

Going Native 2013 – Don’t Help the Compiler, Stephan Lavavej

This presentation from Stephan Lavavej could have been entitled “Compiler Knows Best” – he rockets through numerous examples where the advice is to write less code and let the compiler do the right thing.

Here’s a slide of one of the key messages:

20140207-183930.jpg

Other highlights for me:

  • decltype(auto) coming in C++14 looks very cool (eliminates duplicate code when using auto with decltype for late-specified return values)
  • Don’t call std::make_pair( x, y ) – the T, U are inferred by template argument deduction, so should always be left out (unless you want to force a type conversion when T != typeof(x) e.g. short -> long
  • Use nullptr because it is convertable to all pointer types, but 0 and NULL are always type int

I love the new features of C++11 and couldn’t have written some of the cool libraries I’m working on without them. But – presentations like this make me concerned for the complexity of the language and the steep learning curve that even experienced C++ hires will have to climb.

Leave a comment

Filed under C++, Programming, Video

Going Native 2013 – Effective C++11/14, Scott Meyers

Scott Meyers presented three guidelines from his upcoming new edition of Effective C++:

  • Understand std::move and std::forward
  • Declare functions noexcept whenever possible
  • Make std::threads unjoinable on all paths

The advice on std::move and std::forward echoes thoughts from Scott’s earlier presentation on Universal References. This time, he also talks about efficiency and points out that some standard library methods (such as std::vector::push_back) won’t move unless it can do so using noexcept methods. This is the motivation for the second guideline to use noexcept whenever possible on these key methods (move operators and swap).

The guideline on std::threads harks back to the ongoing discussions in the standards committee – when a joinable (“running”) thread is destroyed, should it block/detach/terminate. Scott advises to use RAII to force the behaviour that you want, and presents a simple class for that purpose.

Leave a comment

Filed under C++, Programming, Video

Herb Sutter GotW95: Thread Safety and Synchronisation

Excellent article on thread safety and synchronisation from Herb Sutter.

A race condition occurs when two threads access the same shared variable concurrently, and at least one is a non-const operation (writer). Concurrent const operations are valid, and do not race with each other.

Guideline: A type should only be fully internally synchronized if and only if its purpose is to provide inter-thread communication (e.g., a message queue) or synchronization (e.g., a mutex).

Leave a comment

Filed under C++, Programming

Unit Testing with GTest and GMock

In recent years, I’ve found myself writing less user interface code and more server code (typically COM servers that are exercised on client workstations or on nodes in a compute farm). Given the lack of a UI for driving and testing the code (excepting spreadsheets), automated tests are vital to achieve a high degree of code coverage.
The Art Of Unit Testing
Given that I’ve been doing this for years now, I was surprised to learn that I haven’t been writing unit tests, as I previously supposed. According to The Art of Unit Testing, the tests I’ve been writing are typically interaction tests. These are useful too, but unless a component can be tested in isolation with tests that run without delay due to network/database interaction, it isn’t a unit test.

Since reading the book, I’ve adopted the Google Test framework for both writing unit tests and implementing mock objects to accompany the tests. Without a good library for writing mock objects, you’re dragged straight back in to writing tests that call other objects in your library. With GMock, you can easily create mock objects and inject behaviour into them in order to test your server code in various scenarios. Using GTest and GMock is easy – just call RUN_ALL_TESTS() in main, and the framework discovers all the unit test you’ve written and launches them:

#include "gmock\gmock.h"
using namespace testing;

// Start writing unit tests here!

int _tmain(int argc, _TCHAR* argv[])
{
    ::InitGoogleMock( &argc, argv );
    return RUN_ALL_TESTS();
}

Here’s a simple example that defines a WeatherStation interface and a UserInterface class. We wish to test the UserInterface, but the weather station isn’t written yet – so we define a MockWeatherStation, and set up tests to invoke the UserInterface in different situations:

#include "gmock\gmock.h"

#include <iostream>
#include <list>
#include <memory>

class WeatherStation
{
public:
    virtual ~WeatherStation(){};

    typedef enum
    {
        North, South, East, West
    } Direction;

    typedef enum
    {
        Optimistic, Pessimistic
    } Outlook;

    // NB Semantics on wind deliberately ugly to show a neat feature in gmock
    virtual void wind( Direction* pDirection, double* strength ) const = 0;
    virtual double rainfall() const = 0;
    virtual std::string prediction( Outlook outlook ) const = 0;
};

class UserInterface
{
public:
    UserInterface( const std::shared_ptr<WeatherStation>& weather_station ) :
        weather_station_( weather_station )
    {
    }

    typedef enum
    {
        Heavy, Medium, Light
    } Range;

    Range rain()
    {
        auto rainfall = weather_station_->rainfall();
        if ( 0.0 <= rainfall && rainfall < 2.0 ) return Light;
        else if ( 2.0 <= rainfall && rainfall < 4.0 ) return Medium;
        else return Heavy;
    }

    Range wind()
    {
        WeatherStation::Direction direction;
        double strength;
        weather_station_->wind( &direction, &strength );

        if ( 0.0 <= strength && strength < 5.0 ) return Light;
        else if ( 5.0 <= strength && strength < 10.0 ) return Medium;
        else return Heavy;
    }

    std::pair<std::string, std::string> predict_range()
    {
        return std::make_pair( 
            weather_station_->prediction( WeatherStation::Optimistic ),
            weather_station_->prediction( WeatherStation::Pessimistic ) );
    }

private:
    std::shared_ptr<WeatherStation> weather_station_;
};

using namespace testing;

class MockWeatherStation : public WeatherStation
{
public:
    MOCK_CONST_METHOD0( rainfall, double() );
    MOCK_CONST_METHOD2( wind, void(WeatherStation::Direction*, double*) );
    MOCK_CONST_METHOD1( prediction, std::string( WeatherStation::Outlook ) );
};

TEST( WeatherStationUserInterface, rain_should_be_heavy )
{
    auto weather_station = std::make_shared<MockWeatherStation>();
    // GMock: specify a simple return value using Return(x)
    // Here, part of the test is that the Mock should be called once,
    // hence the 'WillOnce' call (more than one call would be an error).
    // If multiple calls should happen during the test, 
    // use 'WillRepeatedly' instead.
    EXPECT_CALL( *weather_station, rainfall() )
        .WillOnce( Return(5.0) );
    UserInterface ui( weather_station );
    EXPECT_EQ( UserInterface::Heavy, ui.rain() );
}

TEST( WeatherStationUserInterface, wind_should_be_light )
{
    auto weather_station = std::make_shared<MockWeatherStation>();
    // GMock: specify out parameter values using SetArgPointee
    EXPECT_CALL( *weather_station, wind(_,_) )
        .WillOnce( DoAll( SetArgPointee<0>( WeatherStation::North ),
                          SetArgPointee<1>( 0.5 )) );
    UserInterface ui( weather_station );
    EXPECT_EQ( UserInterface::Light, ui.wind() );
}

TEST( WeatherStationUserInterface, predictions_are_displayed )
{
    auto weather_station = std::make_shared<MockWeatherStation>();
    // GMock: inject more complex logic using C++11 lambdas,
    // and pattern match on the input value
    EXPECT_CALL( *weather_station, prediction(WeatherStation::Optimistic) )
        .WillOnce( Invoke( []( WeatherStation::Outlook _ ) -> std::string
            {
                return "Sunny";
            }) );
    EXPECT_CALL( *weather_station, prediction(WeatherStation::Pessimistic) )
        .WillOnce( Invoke( []( WeatherStation::Outlook _ ) -> std::string
            {
                return "Overcast";
            }) );

    UserInterface ui( weather_station );
    auto predicted_range = ui.predict_range();
    EXPECT_EQ( "Sunny", predicted_range.first );
    EXPECT_EQ( "Overcast", predicted_range.second );
}

When you run the executable, it’s easy to spot if the tests pass or fail:
WeatherStationOutput

As a bonus, Visual Studio 2012 has neat integration for GoogleTest:
WeatherStation

See also

7 Comments

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

C++: noexcept specification generated for destructors in C++11

Andrzej Krzemienski’s blog has this post on the subject of noexcept:

Even if you explicitly declare your destructor without any exception specification, the compiler will add one for you: the same as it would add if it had to implicitly generate the destructor. If you do not like the exception specification generated by the compiler, you have to explicitly specify it.

So if there’s a reason to throw from a destructor (which is typically frowned upon), you’d better declare noexcept(false).

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

Herb Sutter GotW94: AAA Style (Almost Always Auto)

Herb Sutter’s Guru of the Week article on Almost Always Auto is a tour de force covering everything you always wanted to know about auto.

Leave a comment

Filed under C++, Programming