Tag Archives: Visual Studio

How to investigate rebuilds in Visual Studio

You never know when this tip from Kiri Osenkov might come in handy – how to investigate why Visual Studio keeps rebuilding before running, even when you think nothing has changed.

Leave a comment

Filed under Programming

How to stop Visual Studio 2010 showing the post-build Error List

One of my least favourite features of Visual Studio 2010 is that every time my build has an error, it pops up the Error List window. And every time, I switch to the Output window to read the full compiler error because the Error List doesn’t show enough information. In terms of interaction, that’s a major context switch – I’m focussed on the Output window looking at compile errors then BANG, the Error List interrupts my train of thought.

Now, I’ve tracked down this option to stop the Error List appearing:

20130503-184658.jpg

The remaining question is: why put this option under “Projects and Solutions” instead of under “Build and Run”?

Leave a comment

Filed under Programming

Examples of SFINAE (by Jonathan Wakely at ACCU 2013)

I’m currently attending ACCU2013 at Bristol and saw Jonathan Wakely’s presentation on SFINAE (Substitution Failure Is Not An Error) this morning.

This is a traditional SFINAE example using type traits.  true_type and false_type just need to have different sizes, then we can use function template specialization to differentiate between two cases.

typedef char true_type;
typedef double false_type;
template<class T>
true_type is_iter( typename T::iterator_category* t );
template<class T>
false_type is_iter(...);
template<class T>
struct is_iterator
{
  static const bool value =
    (sizeof(is_iter<T>(0)) == sizeof(true_type));
};

void testTypeTrait()
{
 std::cout
    << "Try int " << is_iterator<int>::value << "\n";
    << "Try vector<int>::iterator "
    << is_iterator<std::vector<int>::iterator>::value << "\n";
}

This example later in the presentation really stood out – a step towards Concepts, it shows syntax available today for restricting the types that will compile with a given template (thanks to C++11 aliasing and default arguments for template parameters):

class WidgetBase
{};

class Widget : public WidgetBase
{};

class Bodget
{};

class Decorator
{
private:
template<class T>
using IsDerivedWidget = typename std::enable_if<
        std::is_base_of<WidgetBase, T>::value>::type;

public:
template<class T,
class Requires = IsDerivedWidget<T>>
Decorator( const T& )
{}
};

So if I instantiate Decorator with Widget, it compiles (because Widget derives from WidgetBase), but instantiating with Bodget yields a compiler error (because Bodget does not inherit from WidgetBase).

Widget w;
Decorator decoratedWidget( w );
Bodget b;
Decorator decoratedBodget( b ); // Error

This code all compiles with recent versions of gcc (e.g. 4.7).  Under Visual Studio, only the traditional example compiles (default arguments for function templates are not yet supported, neither is aliasing, not even with the Nov ’12 CTP).

1 Comment

Filed under C++ Code

Online C++ Compilers

Today I took a look at some Online C++ compilers – this would have been very useful when checking portability of some code in my recent post on C++11 Concurrency.

First, here’s LiveWorkspace.org which makes g++ 4.72 and 4.8 available as well as clang 3.2:

MutableReferenceMemberClang

Second, Rise4Fun allows you to try Visual Studio:
MutableReferenceMemberVS

As anticipated, the Counter class (which contains a mutable member of type int&) compiles under Visual Studio, but doesn’t under clang 3.2 or gcc (which is correct according to the C++ standard). What’s great about LiveWorkspace is how quickly you can switch between compilers to see how they like the same code. For example, the amended code that treats int& as a template parameter compiles under g++ 4.7.2 and 4.8, but doesn’t under clang 3.2:

#include <iostream>

template<typename T>
class Counter
{
  mutable T m_t;
public:
  Counter(T t) : m_t(t){}
  void Increment() const { ++m_t; }
};

int main()
{
  int count = 0;
  Counter<int&> counter(count);
  counter.Increment();
  std::cout << count << "\n";
  return 0;
}

Leave a comment

Filed under C++

Writing C++11 concurrency code on Linux Mint with gcc 4.7.2

I’ve written some C++11 concurrency code in VS2012 with the November CTP and wanted to test if it would also run on Linux compiled with gcc – hence the effort to upgrade my laptop over the last couple of days. The upgrade worked fine – I’m quite impressed with Linux Mint and with CodeBlocks. Unfortunately, gcc 4.7.2 has left me disappointed.

Firstly, I tried to compile my whole concurrency project – I was expecting a few minor tweaks (gcc was stricter on how I declare my template functions), then I hit this Internal Compiler Error:

Concurrency.cpp:156:1: internal compiler error: in get_expr_operands, at tree-ssa-operands.c:1035

Apparently, this bug has been fixed but not yet released – it’s due to calling a member function from a lambda in a templated class. So I thought I’d cut my code down, eliminate the lambdas and focus on std::thread and std::condition_variable. Still no joy, this time the program aborted:

LinuxAbort1

In fact, it seems this is a long standing issue. And the code to provoke it is hardly pushing the boundaries of threading:

void sayHelloWorld()
{
    std::cout << "Hello World\n";
}

int main()
{
    std::thread talk( sayHelloWorld );
    talk.join();
    return 0; 
}

Looking on the bright side, gcc 4.8 should be along soon and I’m sure the support for std::thread and lambdas will be working by then. In the meantime, I’ll be hanging out with VS2012 Nov CTP.

1 Comment

Filed under C++ Code

Memory corruption due to C++ code incompatible with C++11 standard

I’m a big fan of C++11 and the new features that have become available, including move semantics.  However, our team found today that a code optimization which worked under VS 2005 was causing memory corruption under VS 2010.

The story goes back to a string holder class a bit like this (if you think BSTRs you’ll be on the right lines, but taking COM out of the picture makes the example clearer):

class CDeepCopy
{
protected:
  char* m_pStr;
  size_t m_length;

  void clone( size_t length, const char* pStr )
  {
    m_length = length;
    m_pStr = new char [m_length+1];
    for ( size_t i = 0; i < length; ++i )
    {
      m_pStr[i] = pStr[i];
    }
    m_pStr[length] = '';
  }

public:
  CDeepCopy() : m_pStr( nullptr ), m_length( 0 )
  {
  }

  CDeepCopy( const std::string& str )
  {
    clone( str.length(), str.c_str() );
  }

  CDeepCopy( const CDeepCopy& rhs )
  {
    clone( rhs.m_length, rhs.m_pStr );
  }

  CDeepCopy& operator=( const CDeepCopy& rhs )
  {
    if (this == &rhs)
      return *this;

    clone( rhs.m_length, rhs.m_pStr );
    return *this;
  }

  bool operator<( const CDeepCopy& rhs ) const
  {
    if (m_length < rhs.m_length)
      return true;
    else if (rhs.m_length < m_length)
      return false;

    return strcmp( m_pStr, rhs.m_pStr ) < 0;
  }

  virtual ~CDeepCopy()
  {
    delete [] m_pStr;
  }
};

CDeepCopy was used as the key into a map. For large data sets with heavily overlapping key values, this was inefficient because each lookup would entail the cost of a copy constructor – this was particularly expensive due to the heap operations. As an optimization, the following technique was used to avoid the copy constructor call in the event of an update operation, yet worked correctly if the operator[]() call led to an insertion.

class CShallowCopy : public CDeepCopy
  {
  public:

  CShallowCopy( const std::string& str ) : CDeepCopy()
  {
    m_pStr = const_cast<char*>(str.c_str());
    m_length = str.length();
  }

  ~CShallowCopy()
  {
    m_pStr = nullptr;
  }
};

So you could do an efficient lookup like this that only caused a deep copy if an insertion into the map was required instead of an update:

int _tmain(int argc, _TCHAR* argv[])
{
  std::map<CDeepCopy, int> entries;
  std::string hello( "Hello" );

  CDeepCopy key( hello );
  entries[key] = 1;

  // Named variable
  CShallowCopy key2( hello );
  entries[key2] = 2;

  // Unnamed temporary variable
  entries[ CShallowCopy( hello ) ] = 3;

  return 0;
}

This code worked as intended in VS2005. However, compiled under VS2010 we were seeing memory corruption in the final case (the one with the unnamed temporary). After some debugging, we realised that under C++11, std::map has an operator[]( KeyT&& key ), that is the key is an rvalue reference – and this form is called for our unnamed temporary case. That avoids calling our CDeepCopy copy constructor, and so the key in the map can be left referencing deallocated memory.

A simple workaround prevents this happening again – declare CDeepCopy( CDeepCopy&& ) as private but omit the definition – this means that the unnamed temporary usage does not compile.

Leave a comment

Filed under C++ Code

Delegating Constructors in C++11

Here’s some code that tries out C++ 11 delegating constructors.  These were announced as part of Visual Studio in the November CTP and avoid the need to refactor common code out of constructors into an “init” function.  There are examples of their use in Stephan Levavej’s excellent video series too.

class Request
{
public:
  enum class Priority{ High, Medium, Low };
  static const Priority defaultPriority(){ return Priority::Low; }

  // Constructor with all parameters fully specified
  Request( Priority priority, const std::string& requestId ) :
      m_priority( priority ),
      m_requestId( requestId )
  {
    std::cout 
    << "Request( Priority priority, const std::string& requestId ) called: "
    << "RequestId " << m_requestId << ", "
    << "Priority " << toString( m_priority ) << "\n";
  }

  // Delegate to fully specified constructor above
  Request( const std::string& requestId ) : 
    Request( defaultPriority(), requestId )
  {
    std::cout 
      << "Request( const std::string& requestId ) called: "
      << "RequestId " << requestId << "\n";
  }

  // Contrived example to demonstrate chaining delegating constructors
  Request( const std::vector<int>& requestId ) : 
    Request( toString( requestId ) )
  {
    std::cout << "Request( const std::vector<int>& requestId ) called\n";
  }

  // Contrived example to show that ~Request() is called if the delegating constructor completed
  Request( Priority priority ) : 
    Request( priority, "Empty" )
  {
    throw std::exception( "This constructor is deprecated, RequestId field is now mandatory." );
  }
  ~Request()
  {
    std::cout 
      << "~Request() called:"
      << "RequestId " << m_requestId << ", "
      << "Priority " << toString( m_priority ) << "\n";
  }
private:
  std::string toString( const std::vector<int>& requestId )
  {
    std::string tmpId;
    for (auto elem : requestId)
    {
      if ( elem < 0 || 9 < elem )
        throw std::exception("Invalid request id, should be digits");
      tmpId.push_back(static_cast<char>(elem + '0'));
    }
    return tmpId;
 }

 std::string toString( Priority p )
 {
   if (p == Priority::Low ) return "Low";
   else if ( p == Priority::Medium ) return "Medium";
   else if ( p == Priority::High ) return "High";
   else
     throw std::exception( "Unexpected Priority" );
 }
 Priority m_priority;
 const std::string m_requestId;
};

And here’s a program that exercises the Request class (this uses musingstudio::initialize to conveniently initialize a standard container):

int _tmain(int argc, _TCHAR* argv[])
{
  std::cout << "\nCall fully specified constructor\n";
  Request fullySpecified( Request::Priority::High, "HeartTransplant-749553" );

  std::cout << "\nCall a delegating constructor\n";
  Request defaultPriority( "BookDelivery-5542" );

  std::cout << "\nCall chained delegating constructors\n";
  Request legacy( musingstudio::initialize<std::vector<int>>( { 1, 6 } ) );

  std::cout << "\nThis should throw without executing the destructor...\n";
  try
  {
    // This should throw due to -ve input, but does NOT execute ~Request()
    // because no constructor call completed
    Request invalid( musingstudio::initialize<std::vector<int>>( {-1} ) );
  }
  catch( const std::exception& exc )
  {
    std::cout << "ERROR: " << exc.what() << std::endl;
  }

  std::cout << "\nThis should throw and execute the destructor...\n";
  try
  {
    // This will throw because no requestId is not specified
    // (contrived example to show that ~Request() is executed
    // because the delegating constructor succeeded).
    Request noRequestId( Request::Priority::Low );
  }
  catch( const std::exception& exc )
  {
    std::cout << "ERROR: " << exc.what() << std::endl;
  }

  std::cout << "\nRemaining destructors...\n";

  return 0;
}

DelegatingConstructorsOutput
As with other Nov CTP features, Visual Studio intellisense hasn’t caught up yet, so expect to see red squiggly lines all over the code if you try this out.

What’s interesting is that it’s now possible for ~Request() to be called if a constructor fails to complete, as long as the delegatee (inner) constructor does complete.

Leave a comment

Filed under C++ Code