Tag Archives: C++11

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

How to downcast a shared_ptr

A lot of the codebase I work on is deployed as COM servers. This means that it isn’t uncommon to pass an array of objects as an of pointers to base (i.e. IUnknown) and then downcast to the specific interface you want using QueryInterface.

I found myself in a similar situation with some more modern C++, where I had a std::vector<std::shared_ptr> and wanted to convert each pointer to a shared_ptr in order to call into some API method. The question is – if you have a std::shared_ptr<T1>, how to cast it to a std::shared_ptr<T2>  (for suitably related T1 and T2)?

This question was already asked on StackOverflow and the answers pointed me at std::dynamic_pointer_cast and std::static_pointer_cast, which are analogous to static_cast/dynamic_cast for raw pointers.

class B
{
public:
  virtual void Print(){ std::cout << "Object type B\n"; }
  virtual ~B(){};
};

class C : public B
{
public:
  virtual void Print(){ std::cout << "Object type C\n"; }
  void BehaveLikeC()  {std::cout << "Behave like C\n";}
};

class D : public B
{
public:
  virtual void Print(){ std::cout << "Object type D\n"; }
  void BehaveLikeD() { std::cout << "Behave like D\n"; }
};

void DoSomething( const std::shared_ptr<D>& d )
{
    d->BehaveLikeD();
}

int _tmain(int argc, _TCHAR* argv[])
{
  std::vector<std::shared_ptr<b>> elements;
  elements.push_back( std::make_shared<C>() );
  elements.push_back( std::make_shared<D>() );

  // Call base class method on all elements
  std::for_each( elements.begin(), elements.end(),
    []( const std::shared_ptr<b>& b ){ b->Print(); });

  // Call C behaviour on all C elements
  for ( size_t i = 0; i < elements.size(); ++i )
  {
    auto c = std::dynamic_pointer_cast( elements[i] );
    if (c ){ c->BehaveLikeC(); }

    auto d = std::dynamic_pointer_cast<D>( elements[i] );
    if (d){ DoSomething(d); }
  }

  return 0;
}

1 Comment

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

Herb Sutter GotW89: Smart Pointers

Herb Sutter’s GotW89 Smart Pointers post includes good reasons to use make_shared/make_unique instead of naked new. Avoiding memory fragmentation is one of those:

Separate allocation

auto sp1 = shared_ptr<Widget>{ new widget{} };
auto sp2 = sp1;

Separate allocation

Single allocation
If you use make_shared to allocate the object and the shared_ptr all in one go, then the implementation can fold them together in a single allocation.

auto sp1 = make_shared<Widget>();
auto sp2 = sp1;

Single allocation

Leave a comment

Filed under C++, Programming

decltype and declval

Good examples of decltype and declval posted on reddit and TheNewCpp.com.

Leave a comment

Filed under C++, Programming

How to choose whether to pass by const-reference or by value

There was a post on the ISOCpp blog last week about passing by const-reference or by value. The full StackOverflow post is Why do we copy then move? and another related post asks Are the days of passing by const ref over?.

First, as my friend and colleague Andy Sawyer pointed out in a conversation, taking a parameter by value leaks implementation detail out of the function so he recommends passing by const reference unless there’s a good reason not to.

Second, whilst passing by value presents the opportunity for the callee to store data using move semantics, the callee has to invoke that explicitly by calling std::move:


#include <string>
#include <iostream>

class A
{
public:
 A( const std::string& s ) :
 str_( s )
 {
   std::cout << "A: s='" << s << "', str_='" << str_ << "'\n";
 }
private:
 std::string str_;
};

class B
{
public:
 B( std::string s ) :
 str_( s )
 {
   std::cout << "B: s='" << s << "', str_='" << str_ << "'\n";
 }
private:
 std::string str_;
};

class C
{
public:
 C( std::string s ) :
 str_( std::move(s) )
 {
std::cout << "C: s='" << s << "', str_='" << str_ << "'\n";
 }
private:
 std::string str_;
};


int _tmain(int argc, _TCHAR* argv[])
{
 A a( "ConstReference" ); // Constructor(char*) then CopyConstructor
 B b( "PassByValue" ); // Constructor(char*) then CopyConstructor
 C c( "PassByValueAndMove" );// Constructor(char*) then MoveConstructor

return 0;
}

PassByValueAndMove

2 Comments

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

Herb Sutter GotW6: Const and Mutable

This item covers ground Herb already presented in this video. He recommends that const member functions must be one of:

  • truly physically/bitwise const with respect to this object
  • internally synchronized so that if it does perform any actual writes to the object’s data, that data is correctly protected with a mutex or equivalent (or if appropriate are atomic) so that any possible concurrent non-const accesses by multiple callers can’t tell the difference.

Similarly, he asserts that the guidelines taught for C++98, that const means logically const but you had a free rein with internal data, is no longer true for C++11 with its memory model and thread safety specification.

This implies stricter best practice on use of mutable member variables. Any time you need to mutate data in a const member function, you should protect it with a synchronisation object to ensure thread safety.

Leave a comment

Filed under C++, Programming