Journal

2012-04-26 CPlusPlus11

Moving on

Time to investigate the new move semantics, or at least what I have understood about it! So what is it? It is a way to specify how object state can be moved instead of copied.

Why is that interesting? Well if copying really isn't necessary, since the object just being copied is never going to be used again ever, then we could just move the state instead of making a copy. No more unnecessary copies. Now this is the normal life for temporaries, so called rvalues. They are created, used and sometimes their values are copied to a resulting variable, a lvalue. During this process a move could be deployed instead of a copy so that the lvalue got its state from a rvalue.

More good news is that the compiler knows when this situation occurs. So your code could benefit from this even without a single change. It is something like the return value optimization but there the compiler can even avoid the move altogether and place the result in the right spot from the beginning. As we will see there seems to be some things that complicates this picture a bit.

How does this work then? In order to specify how the move is to be performed we need to create one new type of constructor, the move ctor. This is like the copy-ctor except that it takes a rvalue reference identified by T&&. Note the notation with the double ampersands. A move ctor for class Class would thus be declared like this:

Class(Class&& c)

This ctor defines how the state is moved from the Class object c instance to this object instance. The body of the ctor will of course depend on the implementation of Class. If it has some members that can efficiently be moved then we are in business.

So with this ctor defined everytime a move can be performed this ctor is called. If we had not defined this ctor then the Copy-ctor would be used instead. So there is a fallback solution - how it worked with old versions of the compiler.

The assignment operator can also be defined in a similar way.

Class& operator=(Class&& c)

2012-04-18 CPlusPlus11

Started to write under the label CPlusPlus11 for the new C++11 stuff. So much time has passed since the standard was released so I guess the old name C++0X is now almost forgotten. Better leave it that way.

2012-04-18 1 CPlusPlus11

Move semantics

Copying big objects has always been a problem and somethings that you want to avoid. Things you have to think about is using reference to const in parameter so you don't get expensive copies. Smart pointer with reference counting is another way to avoid copying. Smart compilers can also avoid some copying that can be optimized away. One example of this is the return value optimization were the temporary object returned from a function is used directly, without copying, to initialize the object holding the value after the function call.

Still there are more temporaries to be avoided and the thing called move semantics or rvalue references are here to achieve that. It seems easy to explain but since much of this with temporaries are, if not hidden to the user, so not as obvious at least, and not what you normally think a lot about when solving coding problems. So we are probably up to one or more surprises here as we go along and I'm afraid that this is probably not a silver bullet for avoiding needless copies.

I'll come back with some code examples shortly.

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.

More...