HomePage RecentChanges About Projects Computers CPlusPlus11 New Archive

HomePage

Welcome! This is where I write stuff...

2012-05-18 Computers

Running single tests with CppUnit

As a C++ programmer you are probably used to, and have accepted, the verbose code you have to write in order to set up a test case with CppUnit. C++ does not have the flexibility like other languages that can know about test cases by naming conventions etc and then set up almost everything automatically. In C++ you need to do most of that yourself by coding it.

So once upon a time you set up the boiler plate code from the CppUnit Cookbook to get the framework for your unit tests installed. Your main test program could very well look like this.

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

int main(int argc, char **argv)
{
  CppUnit::TextUi::TestRunner runner;
  CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  runner.addTest(registry.makeTest());
  bool wasSuccessful = runner.run("", false);
  return wasSuccessful;
}

This is what it takes to run your test cases using the TextUi::TestRunner?. At that time you had a small set of tests but, as the project continued, more tests were added. And now after some time, if you did your homework right, your test suite is anything from small. In fact it is starting to take some time to execute. To long time. When you are developing new test cases it has become a bottle neck in the test, code and refactor loop.

So you would like to limit the number of test cases you run in order to get up to speed. Can it be done? Yes!

The solution lies in that old code you picked from the Cookbook so long ago you hardly remember it. Maybe you, like me, lived long enough with it to assume that it is so it must be in C++ being such a verbose and non dynamic language as it is. Maybe you, like me, have used comments or preprocessor constructs to hide tests. Was I wrong! Single tests can be run. It has been there all the time at my finger tips. If you look carefully at the Cookbook code you'll see that the first parameter of the run method is an empty string. That string parameter is actually the name of the test or the test suite to run! The empty string is only the special case of running all tests!

Now equipped with this knowledge it is easy to change the code to allow us to specify what test to run. The most straight forward is to use the first arg, if present, to the unit test program to be the test case to run. Like this:

  ...
  bool wasSuccessful = runner.run((argc > 1) ? argv[1] : "", false);
  ...

2012-05-11 CPlusPlus11

List of all articles about C++0X or C++-11.

2012-05-09 CPlusPlus11

The future of threading

A major concern these days is how to handle all these cores we have available everywhere. How to program them? C++11 tries to address this problem by including support for threads in the standard library.

The basic stuff for starting and joining threads and synchronization with the help of different types of mutexes is there. Support for low level atomic operations is there to. We might come back to those issues later. Now we will look at the high level support provided by futures and async.

The basic functionality is this. The function async takes nearly anything executable and returns a future object. When you want to have the result from the async call you call the get method on the future object.

   auto f = async(doIt);
   ...
   auto resultFromDoIt = f.get();

Very simple in its basic form. But there is more...

The async execution can be controlled in more detail by specifying a launch policy. It can be launched either async or deferred. If it is called with async policy it will be started asynchronously if it can. You'll get an exception otherwise.

   auto f = async(launch::async, doIt);

When launch::deferred is used it is guaranteed that the function wont run until get is called. What good this is for is another question. Debugging could be one use of it.

Besides the get method there are also methods to poll for a result.

I also said async could be called with almost anything that could be executed. It can take functions, member functions and lambdas. You can pass arguments to the functions.

Be careful though when passing arguments so that they don't go out of scope before the asynchronous computation is finished. All these types of problems are of course still relevant for asynch. Passing arguments by value is one solution to that problem.

2012-05-08 CPlusPlus11

Still moving on

One obvious place for moving objects instead of copying is when making a swap. It is a common operation so there is even a library function for that, std::swap. When used with types that implements the move-ctor and move assignment operator it looks like this.

First we define the move members to illustrate our example.

   ...
   Class(Class&& c) { cout << "Class&& ctor" << endl; }
   Class& operator=(Class&& c) { cout << "Class&& operator=" << endl; return *this; }
   ...

Running this code

   Class c1;
   Class c2;
   swap(c1, c2);

Produces this output:

   Class&& ctor
   Class&& operator=
   Class&& operator=

This tells us that first one of the objects is moved somewhere. A temporary lvalue to hold the value as party of the swap. Then there are two move assignments to get the values back in their new place.

If we would implement this ourselves it could look like this:

   Class temp(move(c1));
   c1 = move(c2);
   c2 = move(temp);

This introduces the new function std::move. It can look a little strange but its job is no more and no less than to typecast its argument into an rvalue reference. This will enable the use of the move members and the output is the same as the example above.

The move feature has been implemented in the standard library containers. So code like this:

   vector <Class> v;
   v.push_back(Class());

will use the move ctor when the new Class object is pushed into the vector. This was legal code before C++11 so this is an example where old code will benefit from the new features without any changes.

2012-05-08-1 CPlusPlus11

Changes to old habits - you need to move to!

With moving available the old habit of always passing non native types as const to ref is not necessary any more. Moving makes call by value and return by value good alternatives.

From my experience return by value was something that was used a lot although the overhead of a copy. Partly because functions are easier to understand that way, return values in parameters is not taught as a good design, and partly because of the return value optimization sometimes got away without a copy anyway and still do!

With C++11 we can safely use call by value when we want that even for complex types. So we should write code like this from now on:

   string manipulate(string s)
   {
      <... perform some manipulation on s ...>
      return s;
   }

Since we are going to change the value on the string we might as well use call by value and change that. The modified value is then returned. The move ctor will kick in an see to that no unnecessary copy is needed.

2012-04-26 Computers

Getting the predefined macros from GCC

Getting the predefined macros from a compiler might be the first thing you should do to learn your tools but in my case it seem to be the last thing I do. To get to the info has in my case often required reading through long an boring manuals. However in the case of gcc there is simple way to get the info directly from the compiler itself.

It goes like this.

echo | gcc -E -dM -

The option -E tells gcc just to run the preprocessor. -dM tells the preprocssor to output all defines.

The final twist is to use stdin to enter the code which in this case is just whitespace. There are other ways do that but I like this pipe version.

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-04-09 Rim

Nytt rim från denna påsk. PåskRimBondBers. Lite i sista laget kanske men det verkar ju vara så det är nu för tiden. Allt för lite tid för poesi, eller vad man nu skall kalla det ;-) Gott slut på påsken!

More...