Category Archives: C++

C++: Race conditions and Data races

According to this discussion on Stack Overflow, we should make a distinction between race conditions and data races. This blog post defines the terms and gives a neat example where the code is modified to exhibit zero, one or both behaviours.

Here’s an example of a race condition – the ordering of the execution affects the outcome (this can occur if one thread checks a value then performs an action, giving another thread the change to mutate the variable in between):

if (x == 5) // The "Check"
{
   y = x * 2; // The "Act"

   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
   // y will not be equal to 10.
}

And here’s an example of a data race – a variable is mutated by multiple threads without synchronisation:

// Execute this function on five threads simultaneously
for ( int i = 0; i < 10000; i++ )
{
   x = x + 1; 
}

In both cases, use of a synchronisation object across all the threads involved (e.g. a mutex) would address the issue.

Leave a comment

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

C++: Function overload preferences

The function overload rules in C++ are sometimes surprising. Herb Sutter wrote an excellent Guru of the Week article on function overload rules some time ago, but here’s some code to differentiate between some of the common overloads:

#include <iostream>
#include <string>

template<typename T>
void foo(T t)
{
    std::cout << "Generic Template function: " << t << "\n";
}

template<>
void foo<int>(int i)
{
    std::cout << "Function template specialization for int: " << i << "\n";
}

template<>
void foo<bool>(bool b)
{
    std::cout << "Function template specialization for bool: " << b << "\n";
}

void foo( double d )
{
    std::cout << "Non-template overload for double: " << d << "\n";
}

void foo( int i )
{
    std::cout << "Non-template overload for int: " << i << "\n";
}

int main()
{
    std::string s = "Hello, World";
    foo(s); // Calls generic template

    bool b = true;
    foo(b); // Calls template specialization

    double d = 1.0;
    foo(d); // Exact match to non-template overload

    int i = 0;
    foo(i); // Exact match (better than template specialization)

    short sh = 255;
    foo(sh); // Not exact match, calls generic template

    return 0;
}

FunctionOverloadOutput

Leave a comment

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

C++: functional programming and type classes

Functional C++ posted an article introducing type classes for C++.

Leave a comment

Filed under C++, 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

How to implement a “virtual” operator<

In order to support a collection of heterogenous objects, I implemented a std::set<std::shared_ptr<Base>> then inherited the derived classes from Base.  That works fine, except that the ordering and uniqueness is controlled by the object addresses, not the values of the derived objects.  Ideally, one would make operator< virtual on Base, but that won’t work here because the signature of operator< for each of the derived classes is different:

bool Base::operator<( const Base& rhs ) const
{  /* implementation */ }

bool A::operator<(const A& rhs ) const
{ /* implementation */  }

bool B::operator<(const B& rhs ) const
{ /* implementation */  }

Instead, this solution follows the “Non-Virtual Interface” idiom and leaves operator< non-virtual. Instead, operator< delegates to a separate virtual method, compares_less. In order to provide a strict-weak-ordering, the objects of distinct types need to be handled too – it’s not enough to fall back to comparing pointer addresses (the addresses could provide an inconsistent ordering).  Here, inter-type comparisons are handled by ordering on the type name (supplied by another virtual method).

// LessThan.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <set>
#include <string>

template<typename Container>
void dump( const Container& elements )
{
  for ( auto it = elements.begin(); it != elements.end(); ++it )
  {
    if ( it != elements.begin() )
    {
      std::cout << ", ";
    }
    std::cout << (*it);
  }
  std::cout << std::endl;
}

class Base
{
public:
  bool operator<( const Base& rhs ) const
  {
    return this->compares_less( rhs );
  }

  virtual std::ostream& dump( std::ostream& os ) const = 0;

  virtual bool compares_less( const Base& rhs ) const = 0;
  virtual std::string type_name() const = 0;
};

class A : public Base
{
  int a_;
public:
  A(int a) : a_(a)
  {}

  int a() const { return a_; }

  virtual std::ostream& dump( std::ostream& os ) const
  {
    os << a_;
    return os;
  }

  virtual bool compares_less( const Base& rhs ) const
  {
    if ( auto pA = dynamic_cast<const A*>( &rhs ) )
    {
      return a_ < pA->a_;
    }
    return this->type_name() < rhs.type_name();
  }

  virtual std::string type_name() const
  {
    return "A";
  }
};

class B : public Base
{
  std::string b_;
public:
  B( std::string b ) : b_(b)
  {}

  std::string b() const { return b_; }

  virtual bool compares_less( const Base& rhs ) const
  {
    if ( auto pB = dynamic_cast<const B*>( &rhs ) )
    {
      return b_ < pB->b_;
    }
    return this->type_name() < rhs.type_name();
  }

  virtual std::string type_name() const
  {
    return "B";
  }

  virtual std::ostream& dump( std::ostream& os ) const
  {
    os << b_;
    return os;
  }
};

std::ostream& operator<<( std::ostream& os, const std::shared_ptr<Base>& b )
{
  b->dump( os );
  return os;
}

struct LessThan
{
  bool operator()( const std::shared_ptr<Base>& lhs, const std::shared_ptr<Base>& rhs ) const
  {
    return *lhs < *rhs;
  }
};

int _tmain(int argc, _TCHAR* argv[])
{
  std::set<std::shared_ptr<Base>, LessThan> elements;

  elements.insert( std::make_shared<A>( 1 ) );
  elements.insert( std::make_shared<A>( 10 ) );
  elements.insert( std::make_shared<B>( "World" ) );
  elements.insert( std::make_shared<A>( 7 ) );
  elements.insert( std::make_shared<B>( "C++ says" ) );
  elements.insert( std::make_shared<A>( 3 ) );
  elements.insert( std::make_shared<B>( "Hello" ) );
  elements.insert( std::make_shared<A>( 5 ) );

  dump( elements );

  return 0;
}

Here’s the output, showing that the A’s and B’s are ordered as expected:
VirtualLessThanOutput

Leave a comment

Filed under C++, C++ Code, 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

C++ Meet-Up London: Ben Hanson on Lexertl

I attended the London C++ Meet-Up on Tuesday 13th August where Ben Hanson presented his work on Lexertl.

The next London C++ meet up is Wednesday, 11 September 2013 at Google Campus, 5 Bonhill St, London, England EC2A.

Leave a comment

Filed under C++, Programming

Scott Meyers Video – Universal References

Scott Meyers posted a video of his Universal References presentation from C++ and Beyond 2012. There’s also an article on the subject in the ACCU magazine Overload Issue 111, but I found the video much clearer (and more entertaining).

Meyers coined the term ‘Universal References’ for instances where the type of a variable or parameter is declared T&& and where T is a deduced type. It may look like an rvalue-reference, but it can also match lvalue-references:

20130813-122646.jpg

so it’s usually a mistake to overload on both T&& and const T& in a template function. Another key point is that, whereas an overload with an rvalue-reference would call std::move (e.g. a move constructor where T is not deduced), an overload with a universal-reference should call std::forward (because you don’t yet know if it’s an rvalue- or lvalue-reference):

20130813-123009.jpg

He also summarises the reference-collapsing rules as “lvalue-references are infectious”, a handy mnemonic from Stephan T. Lavavej.

1 Comment

Filed under C++, Programming, Video

std::sort now guarantees complexity O(N * log N) under C++11 Standard

I learnt recently that in the C++11 Standard, std::sort is required to have complexity O(N * log N) – not “on average N * log N with a worst case O(n^2)”, but guaranteed O(N * log N). This follows David Musser’s paper on Introspective Sorting and Selection.

Musser’s IntroSort uses QuickSort, but also monitors the number of partitions that have occurred. For example, one might use “median-of-3” to pick each pivot, but that could cause the O(N^2) behaviour if pathological sequence is encountered. In the paper, such a sequence is described by construction. IntroSort switches to HeapSort (which guarantees O(N * log N) performance) once the number of QuickSort partitions reaches 2 * log N. Musser proves that the overall algorithm performance remains O(N * log N).

As pointed out on StackOverflow, std::nth_element could be re-implemented with similar benefits:

Ideally exactly the same should apply std::nth_element but the ISO C++ 2011 standard has not tightened up the complexity requirements. So std::nth_element could be O(N * N) in the worst case.

Leave a comment

Filed under C++, Programming