Uniform Initialization Simplifies Testing

In which I demonstrate the use of uniform initialization, and show how it is particularly well suited to unit tests.

In C++0x, there is Yet Another Way to initialize objects, using the {} syntax (uniform initialization). Except, it isn’t really new, it’s the way we’ve always been initializing arrays and structs:

int i[] = {1,4,9};

The difference is we can now use this syntax to initialize any object. Why does this matter, and what is wrong with the old constructor syntax? Nothing is wrong with it in fact, and it will still see a lot of use. But in some cases, {} leads to simpler and easier code.

One area in particular is initialization of containers. It was always a bit of a hassle to initialize for instance a vector, where you would need to do something like this:

    string a[] = {"foo", "bar"};
    vector<string> v(a, a+2);

In C++0x however, you can do

    vector<string> v = {"foo", "bar"};

One area where I find myself initializing containers manually a lot is in unit tests. Here is an example:

#include <gtest/gtest.h>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int count_sheep(const vector<string>& animals) {
    return count(animals.begin(), animals.end(), "sheep");

TEST(TestCountSheep, returns_zero_when_there_are_no_sheep) {
    ASSERT_EQ(0, count_sheep({"pig", "cow", "giraffe"})); //here

TEST(TestCountSheep, returns_all_sheep) {
    ASSERT_EQ(2, count_sheep({"sheep", "cow", "sheep"})); //and here

Note the calls to count_sheep(), where the container is declared and initialized in line, without any mention of string, vector or temporary arrays!

To compile this, you need g++ 4.5 (sudo apt-get install g++-4.5). It might also be possible in Visual Studio 2010 if you are so inclined. This example also uses the Google C++ Testing Framework (sudo apt-get install libgtest-dev). Here is the full command to compile and run the example:

g++-4.5 * -std=c++0x -lgtest_main -lgtest -lpthread && ./a.out

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

2 thoughts on “Uniform Initialization Simplifies Testing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s