Archive for the ‘C++’ Category

How to statically link the C++ REST SDK (Casablanca)

April 1, 2014 19 comments

You are trying to use the C++ REST SDK (Casablanca) in your Windows application. You have one of the following problems:

  • you need Windows XP support
  • when your code executes you receive a debug assertion: _pFirstBlock == pHead
  • you get unpredictable behaviour or random crashing
  • you need to build an application which links against static libraries

You have 30 minutes to solve the problem. Here is how:

The issue is that the C++ REST SDK only supports dynamic linking. The solution is to re-build the SDK with static linking. Read more…


C++: Polymorphic cloning and the CRTP (Curiously Recurring Template Pattern)

August 22, 2013 30 comments

A common problem in C++ occurs when you have an object of an unknown derived type and want to make a copy of it. Consider the following code:

class Vehicle {}

class Car : public Vehicle {}
class Plane : public Vehicle {}
class Train : public Vehicle {}

function make_a_copy(Vehicle *v)
  Vehicle *copy_of_vehicle = new ????(*v);

You can’t just use new Vehicle in this situation because only the base class elements (those from the Vehicle base class) will be available in the copy. So what do we do? Read more…

C++ Class Hierarchies Crash Course: Derivation (“is-a”) vs Composition (“has-a”), and Is a Square a Rectangle?

March 5, 2013 4 comments

In this article I’m going to rattle over some basic design choice dilemmas you might face when trying to organize classes into a hierarchy. We’ll look at standard derivation (the “is-a” relationship), composition (the “has-a” relationship), when to use which, and also touch briefly on interfaces and private inheritance.

Pre-requisites you should know before reading:

  • how to define a class in C++
  • what a constructor is and how to define one
  • the difference between public and private members

The “Is-a” Relationship

Is a square a type of rectangle? Is a rectangle a type of square? Or is a square merely a rectangle with a certain set of properties (identical width and height)? Are circles and rectangles both types of shape, or are they even related at all? The answers to these questions have nothing to do with your natural intuition or experience from the real world (although that helps sometimes), but rather, what you are planning to do with them in your code.

Read more…

Categories: C++ Tags: , , , ,

C++ Explained: Object initialization and assignment, lvalues and rvalues, copy and move semantics and the copy-and-swap idiom

February 27, 2013 8 comments

In this article I’m going to try and clear up some fundamental C++ topics which are a common source of confusion for beginning and intermediate C++ programmers, and programmers coming to C++ from other languages such as C# or Java:

  • the difference between initialization and assignment, which uses of the “=” operator trigger initialization and which trigger assignment, and how to implement them correctly in your own classes
  • the meaning of lvalues, rvalues and rvalue references and how to spot which is which in your programs
  • an introduction to C++11 move semantics
  • when copy and move constructors and assignment operators are called in your classes, and how to implement them
  • reducing the amount of duplicated and error-prone code in constructor and assignment operator implementations by using the so-called copy-and-swap idiom

I won’t be dealing with other initialization or assignment topics here (eg. of in-built or POD (plain-old-data) types, and type conversions), only the initialization and assignment of class objects. It is assumed you understand the following concepts (but not necessarily how to implement them):

  • constructors and copy constructors
  • assignment operator overloading (&operator=)

In the examples below, I will show how to manipulate a class containing a single resource in the form of a std::unique_ptr, which is a single-ownership smart pointer which comes as part of the C++11 standard library, however you can replace this with any resource type which shouldn’t be copied in a bit-wise (shallow copy) manner, eg. any raw pointer or resource handle whose targets should only be freed once no matter how many pointers are held to the resource across object instances, or whose target should be copied if the object instance is copied.

Read more…

Categories: C++

Visual Studio 2012 – Day 1 Annoyances (with an emphasis on C++)

February 19, 2013 3 comments

Update 21st February 2013: added information about Update 2, the C++11 Compiler November 2012 CTP (in two sections) and Find & Replace

Update 16th April 2013: the final version of Update 2 is now released; Update 1 is no longer needed (article updated)

So this is it, huh folks? 16 years of development, and the latest incarnation of the de-facto standard Windows development tool has an interface that might as well be from 1997. The compiler is not much better either it seems, as this C++11 feature support comparison shows: Visual Studio 2012 fails to include such basic support as initializer lists*, uniform initialization*, default and deleted constructors, inherited constructors and non-static data member initializers, while just about managing to shoehorn in raw string literals in the Update 1 package. Yet strangely, Microsoft managed to find time to implement SCARY iterators, checked iterators and futures and promises. SCARY iterators were only an optional part of the ratified C++11 standard.

But, the purpose of this article is to get your life in Visual Studio 2012 running smoothly, so let’s start with the basics.

* these features and others were added in the C++11 Compiler November 2012 CTP, see below Read more…

C++11: Using std::unique_ptr as a class member: initialization, move semantics and custom deleters

October 4, 2012 13 comments

Updated 23rd February 2013: Fixed typos in the code, incorrect use of const, clarified the use of the terms “initialization” and “assignment” to be semantically correct, corrected/clarified references to “constructor” and “assignment operator”, added an explanation of the default copy assignment operator and unique_ptr’s private copy constructor and copy assignment operator.

Updated 12th May 2013: Fixed a factual error regarding standard functions not working as custom deleters in all scenarios, fixed a factual error stating that std::shared_ptr doesn’t support custom deleters (it does), and corrected references to boost which should have referred to std. Expanded the custom deleter section with example cases of new’ing your own resource classes or fetching resources from an external API or factory function. Added text explaining the advantages of using the function object idiom for custom deleters.

The std::unique_ptr class is C++11’s replacement for the flawed std::auto_ptr smart pointer from C++03. std::unique_ptr provides single-ownership pointer semantics and is therefore especially useful when dealing with resource handles which should belong to a single object, and its custom deleter feature (which allows the call to delete to be replaced with an arbitrary function call when the object is destroyed, such as CloseHandle or IUnknown::Release) is great for ensuring resources are closed properly before their handles are freed.

I’m not going to explain how std::unique_ptr or move semantics work here – see the References section at the bottom for some introductory links – rather, I’m going to specifically look at how std::unique_ptr should be used in a non-copyable class (that is, one with a private, or – in C++ 11 – deleted, copy constructor), and specifically, how to make sure the resource is freed exactly and only once.

Read more…

C++11: About Lambda Functions

September 22, 2012 3 comments

One of my favourite inclusions in C++11 – the latest iteration of C++, formerly known as C++0x – is the ability to create lambda functions. Lambda functions are nothing more than unnamed, essentially anonymous functions that you can define in place of where you would usually use a function name, pointer or reference, and they come in particularly handy in combination with STL, although they are certainly not limited to that use. If you have become used to using Boost.Lambda in your applications, C++11’s lambda functions provide a more convenient syntax while also eliminating your code’s dependency on Boost.Lambda.

As with function pointers and references, lambda functions can be defined as variables, passed to and returned from other functions (including other lambda functions) and so on.

Ground Rules

Let us begin with a simple example comparing the use of C++11 and Boost.Lambda when iterating over a few numbers in an STL vector:

Read more…

Printing numbers in binary format in C++

May 12, 2012 15 comments

The problem

You want to display or output a number in binary format. Iostream only has output manipulators for decimal, hexadecimal and octal.

The bad solution

People usually write a loop to do this that iterates over each bit in the integer:

int v = 0x12345678;
for (int i = 31; i >= 0; i--)
    std::cout << ((v >> i) & 1);

There are many ways to do this; the loop above shifts the bit to print into the least significant bit (bit 0) of a temporary and ANDs it with 1 to remove all the other (higher order) bits and leave a 0 or 1. It starts with the most significant bit (31) and iterates down to the least significant bit (0), ensuring that the bits are printed in the correct order.

The good solution

While a looping solution still has applicability in some other languages, there is a much more elegant way to do it in C++ that is often overlooked:

int v = 0x12345678;
std::cout << std::bitset<32>(v);

The C++ standard library includes a container type bitset whose first non-type template parameter specifies the number of bits to store. It includes an overload for operator<< and a conversion constructor for ints, making printing binary numbers a piece of cake! This is a much preferred solution to the messy for loop construct above.

To use bitset, remember to add:

#include <bitset>

at the top of your code.

Good luck!

Categories: C++ Tags:
%d bloggers like this: