All C++ talks from NDC now available


As I’ve previously posted about, there was a great C++ track at NDC this year. It turns out that videos of all the talks are now out. Big thanks to Olve Maudal for putting together this track! And thanks to all the speakers for interesting talks and some nice chats.

You can see my talk “So you think you can int” here, and find my slides here.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Posted in C++. Tags: , , . 2 Comments »

Very Strong C++ Track at the NDC Conference


As someone who doesn’t do web development, and didn’t use to do any .net, I’ve not always been too excited by the Norwegian Developers Conference agenda. This year however, I’m very impressed by the C++ track organized by Olve Maudal et. al.

First of all, there’ll be no less than 13 talks, by Nico Josuttis, Scott Meyers, Andrei Alexandrescu, Hubert Matthews, Mike Long, Isak Styf, Ismail Pazarbasi, Olve Maudal, and myself. In addition, Andrei Alexandrescu will give a two day workshop. Here’s the full list:

ndc

See the full agenda at ndcoslo.com, especially Wednesday and Thursday. I’ll be talking about ints. If you think that sounds like a narrow topic, rest assured there’ll be a char too! Oh, and a secret tip, if you’re a member of Oslo C++ Users Group, contact me for a discount!

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Posted in C++. Tags: , , . 3 Comments »

New job!


Today was my first day at my new job as a staff engineer at Outracks Technologies. Outracks is a small startup in Oslo creating Uno, the world’s first hybrid CPU/GPU programming language, and Realtime Studio, a powerful, easy-to-use IDE for real-time graphics in 2D and 3D. In other words, theywe’re the coolest technology company in Norway! :)

For a one-minute intro to Realtime Studio, check out the brand new product video. Today also marked the release of the Faraday milestone release, which comes with a video of its own. If you want to check out Uno and Realtime Studio, don’t hesitate to sign up for the closed beta!

Discovering the demoscene back in 1995 was the main reason I got into programming in the first place, and with this job it really feels like I’ve come full circle.

Since Uno is not C++ (even though it compiles down to it on several of our target platforms), I will probably not post much more about it here. If you’re interested in keeping up, you can follow me and Outracks on Twitter, and like Outracks on Facebook.

CppQuiz.org officially launched!


The Story (you can skip this part)

Back in April I went to the excellent ACCU 2013 conference. I had been playing with the idea for an online C++ quiz for a while, but decided I didn’t have the time to do it. Then, after a few glasses of wine at the conference dinner and a few more Bath Ales in the bar, I went to my room to get some sleep. But it couldn’t hurt to do a little bit of coding, could it? Add to that the train to London next day, and the plane to Oslo, and the first version of CppQuiz.org was born.

I spent a few more days on it this summer, and since then it has been functionality complete (enough) and stable, so today I removed the “beta” header. I also realised I had forgotten to blog about it, which is kind of silly. How to market a quiz about C++? What about on your own C++ blog?

What is it

CppQuiz.org is (as you might have guessed by now) an online C++ quiz. Each question is a full C++ program, and you are to figure out what its output is. I stole this format from Olve Maudal‘s pub quizzes, but with one major difference: While his quizzes are about what happens on his computer (which is very interesting for a more interactive format), CppQuiz.org asks about what the standard mandates the output to be. If the example code doesn’t compile, or has unspecified/undefined behaviour, you answer that.

The site will just keep throwing questions at you (training mode), optionally giving you a hint and finally give you a full explanation of the answer, with references to the C++11 standard. If you want, you can however start a new quiz (quiz mode), and get a fixed number of questions. At the end you get a score, and a link to give your friends to see if they can beat you. Neither mode requires you to register or log in.

How you can help

If you like the quiz and want to help, there are many ways to do so:

Thanks guys!

Finally I wish to thank a few people. Olve Maudal gives the world’s best C++ pub quizzes, and was my biggest inspiration for creating the site. He also has a fascinating, deep understanding of C and C++, and is an all-around great guy. He even sent me all his C++ quiz material to use for inspiration. See, I told you he is a great guy.

Several people have also contributed their own questions. KrzaQ2 did several, Lars Storjord and others also did. Mikael Kilpeläinen and Fernando Cacciola sent me some of their material. Jon Jagger, Peter Sommerlad, Björn Fahller and several other ACCU members provided good feedback. (I do hope you’re an ACCU member?) Oh, and Webfaction is a highly recommended hosting company. They don’t sponsor me or anything, but their customer service is the best.

Now go take the quiz!

If you enjoyed this post, you can subscribe to my blog, or follow me (@knatten) or @CppQuiz on Twitter.

Posted in C++. Tags: , , . 7 Comments »

Prefer Using References With Range Based For Loops


Now and again I see people forgetting the & in range based for loops, like this:

    for (auto a : a_vec)
    {
    }

What some people seem to forget, or don’t know, is that this creates a copy of the element for each iteration. Unless you actually need a copy, there is no need to perform it. And if the objects you are copying are any larger than a built-in type (integer, pointer etc.), there is a potential performance penalty. So by default, do this instead:

    for (const auto& a : a_vec)
    {
    }

Notice the &? Now you get a reference instead of a copy, which is typically cheaper. Here is the full program:

#include <iostream>
#include <vector>

using namespace std;

class A
{
public:
    A() = default;
    A(const A& rhs) { cout << "Copy" << endl; }
};

int main()
{
    vector<A> a_vec(2);

    cout << "Range based for without &" << endl;
    for (auto a : a_vec)
    {
    }

    cout << "Range based for with &" << endl;
    for (const auto& a : a_vec)
    {
    }
}

And its output:

Range based for without &
Copy
Copy
Range based for with &

Afterthought: Why?

Why are people doing this? It might be that people are used to iterating with iterators, where you get a cheap copy of the iterator, not the actual object:

    for (auto a = a_vec.cbegin(); a != a_vec.cend(); ++a)
    {
    }

Here, a is an iterator, not the actual object, so copying it is inexpensive.

As usual, the code for this blog post is available on GitHub.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Fighting FUD – Introducing C++11 to Legacy Programmers


I’m at the ACCU 2013 conference, and this morning Bjarne Stroustrup held a keynote about C++11. One of his points was that full adoption of C++11 will take some time, due to compilers, libraries etc. lagging behind, but also due to many programmers not wanting to use new things in general. What can you do about it? Bjarne briefly suggested we fight the FUD by starting to introduce the very simplest features that just make everyone’s lives easier. Here is my take on that.

Simple feature #1: Uniform Initilaization

Initializing containers used to be painful. For example, initializing a vector of ints required a long list of push_backs, or something like this:

    int tmp_v[] = {1, 1, 2, 3, 5, 8};
    vector<int> old_v(tmp_v, tmp_v + sizeof(tmp_v) / sizeof(tmp_v[0]));

Now however, we can do this:

    vector<int> new_v = {1, 1, 2, 3, 5, 8};

Even the most hard-core “I don’t need all that new stuff” legacy programmer will appreciate that. Btw, I think this is especially useful in unit tests, where you typically initialize a lot of data manually. (Those legacy programmers probably “don’t need all that new unit testing stuff” either, though.)

This becomes even more important when you have more complex containers:

    vector<pair<int, string>> ints = {{1, "one"}, {2, "two"}};

Simple feature #2: Type deduction

Let’s say we want to print out that vector of pairs from the previous example. This is how you’d do it in C++03:

    for (vector<pair<int, string>>::const_iterator it = ints.begin(); it != ints.end(); ++it)
    {
        cout << it->first << ":" << it->second << " ";
    }

That vector<pair<int,string>>::const_iterator is a bit cumbersome, right? Well, in C++11 we can let the compiler figure out the type for us:

    for (auto it = ints.begin(); it != ints.end(); ++it)
    {
        cout << it->first << ":" << it->second << " ";
    }
    cout << endl;

Note that auto is resolved compile-time, this is not dynamic typing. But we can do even better:

Simple feature #3: Range based for

    for (auto& elm : ints)
    {
        cout << elm.first << ":" << elm.second << " ";
    }
    cout << endl;

This really is as simple as it gets. Notice that the type of elm is no longer an iterator, it is a reference to the element. This means you no longer have to dereference the iterator, and things become even simpler. (Not having to dereference is a bigger issue when the containers store pointers, and you end up doing (*it)->member.)

(Not so?) simple feature #4: Lambdas

The first three features should be fairly simple to convince anyone to use. I would however argue that it should be fairly simple to make an argument for the simplest uses of lambda functions too.

Lets say we want to find an element in that vector<pair>. To do that, we need a predicate function/functor. In C++03, we would need to either do something with std::bind_1st / std::bind_2nd, or write our own predicate like this:

    class CompareString
    {
        public:
            CompareString(string s) : s(s) {}
            bool operator()(const pair<int,string>& p) { return p.second == s; };
        private:
            string s;
    };

    auto it = find_if(ints.begin(), ints.end(), CompareString("two"));

We are not really interested in making that class. All we want is the content of operator(). Wouldn’t it be nice if we could just paste that code directly in the call to find_if? Something like this?

    auto it2 = find_if(ints.begin(), ints.end(),
        bool operator()(const pair<int,string>& p) { return p.second == "two";});    

With lambdas, we can:

    auto it2 = find_if(ints.begin(), ints.end(),
        [](const pair<int,string>& p) { return p.second == "two";});    

For the purpose of this article, [] can be read as “lambda function follows:”. Notice that we don’t even have to specify the return type, as it can be deduced by the compiler.

Conclusion

That’s it! Just a few simple things to start introducing in you code base, to fight the FUD and convince the legacy programmers that C++11 is nice. (And sorry if this blog post feels a bit rushed, I wrote it during lunch at ACCU 2013. Now I’m off to see my friend Mike Long talk about legacy code base restoration projects.)

As usual, the code for this blog post is available on GitHub.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

How to avoid includes in headers


I have now written twice about why you should minimize the use of include in header files. As one reader on Reddit politely put it (“crap article”), it is about time I write a post about how to do that.

There is mainly two things you can do:

  1. Reduce the number of headers you include.
  2. Reduce the contents of those headers.

1: Reducing the number of includes

Why do you need includes in the header in the first place? When you compile a file that includes header A, all the names that are used in header A need to be defined. So if header A uses an name defined in header B, header A should include header B (or else anyone who includes A will have to include B as well).

What do I mean by “using” a name then? Basically everything that mentions the name, except as a pointer or reference. Some examples of using a name:

SomeClass f; //Creating an object
some_function(); //Calling a function
class Derived : public SomeClass; //Inheriting from a class

Some examples of mentioning a name but not using it (only needs access to a declaration, not the definition):

SomeClass* f1; //Declaring a variable of pointer type
SomeClass& f2; //Declaring a variable of reference type

As soon as you want to use those though, they must be completely defined:

f1->function(); //Needs definition
f2->member; //Needs definition

Also note that the new type of enum, (enum class) only needs to be declared to be used, as long as you don’t actually mention its value:

SomeEnum e; //Declaring a variable of oldschool enum type needs definition.
SomeEnumClass e; //Declaring a variable of newschool enum type does not need definition...
SomeEnumClass e = SomeEnumClass::VALUE; //...but using a value does.

So given this knowledge, how do we reduce the number of includes in headers?

The first thing to do is to make sure you only include what is necessary to get the header file to compile. If you have a class definition in class.h and the implementation in class.cpp, the latter will typically need includes that are not needed by the header, and so should be put in the cpp. A simple way to check that you don’t have any unnecessary includes is to create an empty cpp file that only includes class.h. If it compiles, all the necessary headers are there. Then you can try commenting out includes in class.h and see which ones actually need to be there. Move the rest down to class.cpp.

The next thing to do is to check whether you actually need access to the definitions, or if a declaration will do. Try commenting out one #include at a time, and checking which names the compiler complains about. Then see if you are actually using that name, or if you are merely holding a pointer or a reference to an object of the type. If so, move the include down to the .cpp file, and add a forward declaration. Here’s an example:

#include "stuff.h"

class Ohlson
{
public:
    void doThings(Stuff* stuff);
};

The include stuff.h in not needed, as we never use stuff. Instead, we can use a forward declaration:

class Stuff; //Forward declaration instead of include

class Ohlson
{
public:
    void doThings(Stuff* stuff);
};

In the definition of Ohlson::doThings(Stuff* stuff) however (typically in ohlson.cpp), we probably need access to the definition of Stuff and need to include it.

So one of the things that will reduce the number of includes in headers is using pointers/references instead of values. There are other considerations to design as well though, so I would not advocate moving from values to pointers without considering the full picture.

Another thing that helps is to have the definition of functions in the .cpp file instead of the .h file. This however prevents inlining, so again, use caution.

A final technique that could help is the Pimpl Idiom. Briefly explained, instead of keeping your private members in the header, you keep them in a struct in the .cpp file. This means you don’t need access to their definitions in the header file, and can move their respective includes down to the .cpp file as well.

Reducing the content of includes

The other thing you can do to reduce the negative effects of includes in headers, if you cannot avoid them, is to reduce the content of those included headers. Here are some techniques:

C++ supports several paradigms, but a good recommendation for most is to depend on abstractions instead of implementations. In object oriented programming, this is done by programming to interfaces. C++ doesn’t have an explicit interface concept, but a class with only pure virtual methods is the same thing. Interfaces should also be kept small and focused. This means an interface should be very quick to compile, reducing the pain of having it included in many files. You will however still need to recompile all the files that include it when it changes, but the more focused it is, the fewer files will depend on it.

A generalization of the above is to avoid large inheritance hierarchies, even if you aren’t able to only use pure interfaces.

If you absolutely need to include a file in your header, but it is one that you own, you can reduce the content of that file by applying the techniques mentioned in the first part of this article to that file. (This is just section 1 seen from the other side of the table.)

A less straightforward technique is to be a bit clever with your templates. Templates are usually completely defined in header files, meaning that a change in the implementation triggers a recompile of everything that uses that template. There is however ways to move the implementation of templates out of header files, for instance as in this Dr. Dobbs article. C++11’s extern template can also help reduce compilation time. Avoiding the use of templates completely of course also solves the problem, but there was probably a reason why you wanted them in the first place.

One final technique that cannot go unmentioned is precompiled headers. While I don’t like what they do to dependencies, I consider them a necessary evil in medium to large projects to keep compile-times reasonable. Precompiled headers are very well explained in the first link in this paragraph, but here’s a short version: Headers can take a long time to compile. If they also change rarely, it would be nice to be able to cache them, and this it what precompiled headers does. In Visual Studio for instance, you put these includes in a file conventionally called stdafx.h, and then include stdafx.h in all your cpp files instead of the actual headers you need. The compiler then only has to compile them once. Headers from the standard library are typically placed here, and third party headers are also usually a good fit.

Those are the techniques I could think of, but I am sure I missed some. Which are you favourite ones? Which did I miss? Which of them are silly? Please use the comment section below.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

Follow

Get every new post delivered to your Inbox.

Join 392 other followers