Tag Archives: C++

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

How to Integrate GTest into Visual Studio 2010

I’m using GTest for C++ unit tests and have found a neat way to integrate this into Visual Studio 2010. It’s very low-tech, but works pretty well – see http://stackoverflow.com/questions/6414788/how-can-i-add-a-custom-command-to-visual-studio

  • Go to Tools | External Tools… to add the command line running your GTest executable
  • In the dialog, browse to your command, add the command line arguments, and be sure to select “Use Output window”
  • Count up the external tools to identify the index of your new one (starting at one, not zero)
  • Create/customize a toolbar – click “Add Command” and pick your new tool under category Tools, External Commands 1,2,3 … n
  • Edit the name using “Modify Selection”

That’s it! Now, your command runs inside Visual Studio and writes into the output window. Even better, if there’s a test failure that includes the source location, you can double-click on it to go to that line in the editor.

1 Comment

Filed under C++, Programming

VC++ 2013 Class Layout Change and Wasted Space

Bruce Dawson posted about class layout incompatibilites in Visual C++ 2013.

Leave a comment

Filed under C++, Programming

Going Native 2013 – ‘new’ STL algorithms

I’ve watched a few of the Going Native 2013 videos now and, whilst I was impressed by Herb Sutter’s games written in Cinder, I particularly like the slide and gather algorithms demonstrated by Sean Parent in his C++ seasoning presentation:

template<typename Iter>
auto slide(Iter begin, Iter end, Iter target) -> std::pair<Iter,Iter>
{
    if (target < begin) return std::make_pair( target, std::rotate(target, begin, end) );
    if (end < target) return std::make_pair( std::rotate( begin, end, target ), target );
    return std::make_pair( begin, end );
}

template<typename Iter, typename Pred>
auto gather(Iter begin, Iter end, Iter target, Pred predicate) -> std::pair<Iter,Iter>
{
    auto start = std::stable_partition( begin, target, std::not1(predicate) );
    auto finish = std::stable_partition( target, end, predicate );
    return std::make_pair(start, finish);
}

Whilst I haven’t used std::rotate or std::stable_partition, I’m sure to use these two algorithms built on top of them, probably because their behaviour is so much easier to describe.

Leave a comment

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

Flat Containers in Boost

Jon Kalb posted an article on flat containers in boost.

Alex Stepanov, the STL’s creator, has been quoted as saying, “Use vectors whenever you can. If you cannot use vectors, redesign your solution so that you can use vectors.”

The Boost Container library has a family of flat_* containers that have associative container interfaces and semantics, but are implemented as sorted vectors

Leave a comment

Filed under C++, Programming

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++: 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

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