Category Archives: 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

Bruce Dawson on a VS Compiler bug and heap tracing tools

Bruce Dawson found a compiler bug – and demonstrated a couple of good tools for tracing heap allocations.

Leave a comment

Filed under 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

Why call std::move on a variable that is already T&&?

A StackOverflow question asks why it is necessary to call std::move on a parameter when implementing a move constructor, given that the parameter is already declared T&&?

Named rvalue references are lvalues. Unnamed rvalue references are rvalues.

In other words, if you don’t explicitly move a into b X b = std::move(a); then you haven’t declared that you’ve finished with a, which is a named variable – so the compiler will call X’s copy constructor instead of X’s move constructor.

Leave a comment

Filed under C++, Programming

“Contextually converted to bool”

Chris Sharpe blogged an example of how marking operator bool() explicit neededn’t necessitate any overhead when using that type in a simple if condition:

An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (8.5). Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (8.5). The effect of either implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

Leave a comment

Filed under C++, Programming