CPlusPlus0X

Go to CPlusPlus11 for the new standard. This page was created just before the release of the new standard and thus got the old name. It is kept here for reference for a while.

There is a new standard for C++. I'm thinking of describing it here in the hope of learning it at the same time. It was once known as a coming standard and was as such named C++0X and my wiki pages still have that name.

These are the sources to info about C++11 and C++0X I have used so far:

Below follows the blog which means the order can be far from pedagogic in fact it is in reverse pedagogic order! See CPlusPlusArticles for all blog posts ordered by date.

2012-02-27 CPlusPlus0X

Giving up on static linkage

I've been struggling with getting the treading examples working but with no luck. An exception is thrown. Finally I got a hit on the net that suggested that the static linkage didn't work properly. It seems to be so. With dynamic linkage it works fine.

We thus need to change how we build and run the programs. Remember the tool chain description 2010-06-18_CPlusPlus0X?

We now need to drop the -static flag when we compile and link. We also need to add the -pthread flag for using threads.

$HOME/bin/gcc -std=c++0x -pthread

But this is not enough. We need to tell the runtime where the shared library files are located as they are not in the standard place. The environment variable LD_LIBRARY_PATH is used for that. Add this below in order to run the program.

export LD_LIBRARY_PATH=$HOME/lib

Replace with whatever location you have on your toolchain.

With this in place we are ready to look into the world of threads and threads support.

2012-02-24 CPlusPlus0X

Strongly typed enums

The old enum definition was a bit lame. Enums were almost interchangeable with an int and still not. This could cause some problems. With C++11 these problems have been resolve by introducing the enum class. An enum can be defined like this:

enum class Fruit
{
  Apple,
  Banana,
  Kiwi = 100,
  Pear /* = 101 */
};

That new type has the following properties:

- It is type safe. The type is not implicitly converted to int nor comparable with int. If you want to turn such an enum into an int you need to use a cast. - The underlying type of the enum is known and can even be specified. Default type is int. - The scope of the enumerators are within the enumeration. So enumerations defined at the same scope can have enumerators with the same name.

2012-02-09 CPlusPlus0X

Explicit virtual overrides

There were some, small!?, problems regarding controlling derivation and defining virtual functions. Two new constructs override and final are introduced to resolve that.

override

The problem here was that you could by mistake create a new function when you really just wanted to override a function. By appending override to the function declaration we say that this function must override a function with the very same signature. Like this:

class Derived : public Base {
public:
   virtual void func(int) override;
};

final

With final derivation can be hindered. This can be applied both to whole classes and explicit functions.

class CantInheritFromThis final {
};

class Base {
   virtual void cantOverride(int) final;
};

Note that final and override are not keywords. They are treated as identifiers with a special meaning in the places just described. In other places they can be used just like normal identifiers.

2012-02-08 CPlusPlus0X

constexpr

To allow more expressive constant expressions C++-11 introduces the keyword constexpr. Now with constant expression we really mean constant expression evaluated at compile time. So by saying that a function is constexpr means the compiler will compute the value at compile time. It can look like this:

constexpr int doubleIt(int x) {return x * 2;}

This function doubles its argument. Because it is declared with constexpr it can be used in places where a constant expression is needed. So now we can do this:

char char_array[doubleIt(6)];

Now there are some limiting rules for these constexpr functions. The body should be a single statement of the form "return expression;". The expression must only refer to other constexpr expressions. The later sounds reasonable since how could it be evaluated at compile time if not all parts of it was constant?

That could sound rather limiting but since functions can call other functions or even call themselves recursively some complexity can be computed. The conditional operator "?" is also allowed.

The constexpr functions is not limited to be used only for compile time computing. If called with a non const argument the function is computed in runtime.

2011-12-20 CPlusPlus0X

Object construction made easier

There are three things made for easier object construction. Non static members can be initialized in a new consistent way, constructor can delegate construction to other constructors and constructors can be inherited. The last improvement has as of this writing not been implemented in gcc yet so we'll come back to that later. For the other two read below.

Non static member initialization

Before non static members had to be initialized in the constructor. Now they can be initialized directly in the class definition like this:

class Initialized
{
  public:
    Initialized();
    Initialized(const string& initialValue);

  private:
    string initializedMember = "Hey I'm initialized right here!";
}

This is so clear that it is good on its own. Before you had to initialized the member in both of the constructors. This lead often to the need to define a special method just for doing the common construction and the you had to call that one in the body of all constructors. No need for that now. Simply initialize the member in a clear and concise way in the class definition.

Constructor delegation

Similar to the member initialization improvement is constructor delegation. This means that a constructor can delegate the construction to another constructor. So you can keep all the construction code to one constructor and avoid the extra initialization member that way. The syntax is the same as for initialization lists.

class Delegation
{
  public:
    Delegation(const string& initialValue) { <complex initialization code> };
    Delegation() : Delegation("Initial value") { ... };
}

The default constructor of Delegation delegates the construction to the constructor taking a string parameter by calling it in the member initialization list and passing in the value. This way all the nitty and gritty initialization details can be placed in the first constructor.

Note that if delegation is used no member can be initialized in the initialization list. Other assignments will have to wait until the body of the constructor.

2011-11-25 CPlusPlus0X

Getting multiple angle brackets right

A mostly embarrassing thing with good old C++ was that multiple right angle brackets ">>" was defined as the right shift operator, period! So with nested template definition you loose and had to insert extra spaces to make the parser behave. So this was what you had to write to define a list of lists of integers:

list<list<int> > listOfListOfIntegers;

See the extra space there? Could it be interpreted as a right shift? Hardly.

C++11 fixes this by allowing multiple right angle brackets as closing template delimiters where it can't be confused with the right shift operator. So we can now write this:

list<list<int>> listOfListOfIntegers;

Feels right doesn't it!

Note that the old notation is of course still valid. You can have spaces between the closing delimiters. So this does not break old code.

2011-10-19 CPlusPlus0X

New keyword nullptr

Maybe what can be called a smaller correction in the new standard is the introduction of the keyword nullptr. In C++ 0 is allowed as the value for a null pointer. Often the macro NULL, defined to 0, is used to express that this is a pointer.

However 0 is of type int. So in a overloading scenario like this:

void func(int);
void func(char *);

The call, func(NULL), will call func(int)!

This might not be an overload situation that happens that often but still it is a problem. Maybe it is equally important that there now is a keyword that truly is a null pointer constant. No need to use NULL nor 0 any more for pointers.

Further nullptr has the semantics that you would expect with pointers. Here backward compatibility was regarded as important. So a nullptr in a bool context is false. Like this:

bool trueValue = !nullptr;
bool falseValue = nullptr;

Note that the constant 0 is still a valid null pointer constant for backwards compatibility reasons. So the nullptr keyword is not likely to break old code.

2011-09-15 CPlusPlus0X

More on Lambdas

As we saw in the example with computing the sum we could in the lambda bind a variable from the defining scope. This is also known as a closure. The functions is closed over its free variables. That is great, it has fancy name, can we look at more ways how to use it?

One new aspect is if we look at capture by value. In the sum example we bound sum by reference so we could update it inside the lambda. If we want the value at the creation time of the lambda we capture by value instead. It looks like this:

[var] (... // capture variable var by value
[=] (...   // capture all variables by value
int divBy = 2;
auto divBy2 = [divBy] (int x) { return x / divBy; };

divBy = 4;
auto divBy4 = [divBy] (int x) { return x / divBy; };

assert(4 == divBy2(8));
assert(2 == divBy4(8));

Yes, the first lambda divides by 2 and the second by 4. All because divBy is captured by value when we defined the lambda.

To go further, we can even bind this. So accessing and calling members from a lambda expression is possible. Let us define a class (using a struct to make the example less verbose)

struct Name 
{
   string name;
   void me() { cout << "I'm: " << name << endl; }
   function<void()> callMe() { return [&]() { me(); }; }
};

The first function member me is easy to understand. It prints the name of the object.

The second member callMe requires some explanation. First it introduces std::function. Let us settle for now that it declares a callable type taking no parameters and returning void. The lambda itself binds all members by reference and calls the member me.

Using it can look like this:

Name al {"Al"};
auto gl = al.callMe();
gl();    // Prints "I'm: Al"

This is like a function object but created with less typing.

2011-09-07 CPlusPlus0X

Lambda expressions

For defining small functions at the very spot they are used C++ introduces lambda expressions. A lambda expression is like a short function that can be used where a normal function would be called. Here is an example of a predicate functions that returns true for odd numbers:

[](int x) { return x % 2 == 1; }

This specifies a lambda expression taking one int parameter. The return type is defined by the type of the return statement. Yet a place where compact notation has been chosen. It can be put to use in a count_if algorithm like this:

list<int> numbers {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numberOfOdd = count_if(numbers.begin(), numbers.end(), [](int x) { return x % 2 == 1; });

No need to define a local predicate functions. The lambda expression can be used right in place.

But there is more. We just saw that a lambda can take arguments but it can also bind to variables in the scope of its creation like this:

int sum = 0;
for_each(numbers.begin(), numbers.end(), [&sum](int x) { sum += x; });

The variable sum is available in the lambda and it is accessed by reference. The [&sum] notation in the beginning of the lambda expression defines this binding.

In the next posting we'll look more into the closure aspects of lambdas.

2011-07-31 CPlusPlus0X

Range based for loops

Looping over containers is a very common task so it should be easy two write and easy to read. In C++ is was even worse than in many other languages due to the verbose code for treating iterators. We have seen that the new meaning for the auto keyword has resolved that to some extent. But it gets better.

The new construct for range based for loops makes it even easier. For example: To loop over a list of ints we can write it like this:

list<int> numbers {1, 2, 3, 4, 5};

for (int& i : numbers)
{
   i += 2;
}

This will loop over the list and increment each item by two. Note the very compact and clear notation.

auto works too so you could even write the loop like this:

for (auto & i : numbers)
{
   i += 2;
}

More...