Get Started With Boost in 3 Minutes

Boost is simply a collection of C++ libraries that provide lots of fun things to do in C++ without you having to write the code yourself.

For example, Boost contains libraries to help you with mathematical calculations, regular expressions, smart pointers and even python integration.

Parts of Boost have already been integrated into C++11, but if you (or your organisation) is not quite ready for C++11 yet, or you want to play with the other Boost libraries, you can get to grips with it really easily in just 3 minutes.

This guide covers the header only libraries (i.e. most of them). I’ll take a look at the compiled libraries next week.

 

1) Install Boost

As root/sudo type:

yum install boost-devel

You must install ‘boost-devel’, rather than just ‘boost’, or you will only get the compiled libraries and not the headers. Since boost is mostly header-only libraries, this won’t be much use!

Time taken: 30 seconds

 

2) Write yourself a program and Boost it!

In order to use the boost methods, you must include the namespace qualifier.

If you don’t, your compiler will tell you that the methods are undefined and you may end up on a wild goose chase trying to ensure that boost is installed correctly and that the header files are being found. Stop right there!

You can either include it in one line (as I have done here), or you can individually qualify each method you use, e.g. with boost::gregorian::.

 

//include the boost header file for the library you want to use
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>

int main()
{
    //don't miss this out or it won't compile
    using namespace boost::gregorian;

    //construct a date object
    date xmas(2011,Dec,25);

    //print the day of the week
    std::cout << "Christmas 2011 falls on ";
    std::cout  << xmas.day_of_week() << std::endl;

    //add a (leap) year
    date_duration leapyr(366);
    xmas += leapyr;

    //print day of the week next year
    std::cout << "Christmas 2012 falls on ";
    std::cout << xmas.day_of_week() << std::endl;

    return 0;
}

Time taken: 2 minutes

 

3) Compile and run your program

g++ boost.cpp

The output should be:

Christmas 2011 falls on Sun
Christmas 2012 falls on Tue

Then sit back and feel very pleased with yourself.

Time taken: 30 seconds

 

If you thought that was fab and want to learn what else you can do, full documentation is available here.

Can’t argue with that!

Dynamic Memory in C++ (new and delete)

We looked at dynamic memory in C last week, so let’s compare it with dynamic memory in C++.

Allocation

In C++, if you want to allocate on the heap rather than the stack, you need to use the new operator.

Just like the C equivalents, the new operator returns a void* pointer to the block of memory that has been allocated.

There are two versions of new, the first returns a single item:

int* x;
x = new int;

The second, using square brackets, returns an array of items:

int* x;
x = new int[16];

Checking for success

C allocators return NULL and set errno when they fail, which you should explicitly check for.

In C++ however, an exception is thrown (bad_alloc). If you don’t have the code in place to catch the exception, your program will terminate.

You can force C++ to behave like C by passing the nothrow argument to new:

int* x;
x = new(nothrow) int;

Now new will behave like a C function and set x to NULL if it fails.

Of course, if you do this, you’ll remember check for a NULL value before using the pointer, won’t you?

Clearing up

Just like in C, you MUST remember to clear up after yourself when you’ve spent the afternoon happily declaring memory on the heap.

To do this, you need to call delete. There are two versions of delete that match the two versions of new:

//for single objects
delete x;
//for arrays
delete[] x;

What if you use the wrong one?

If you forget to use the brackets on an allocated array, you will only delete the first element. The others will remain inaccessible in memory, causing a memory leak. And you don’t want that to happen, do you?

If you use the bracketed version on a single object the behaviour is undefined. Which, if you’re unsure, means you can’t rely on the result to be anything you might expect 🙂

Can you mix and match between new, malloc, delete and free?

No. Never do this!

First off, it’s just plain wrong to mix functionality from two separate languages (even though you can).

Second, new and delete are used in C++ because they call the constructor and destructor of an object respectively. The C equivalents, malloc and free do not do this.

So, if you create an object with malloc, any work done in the constructor will not happen.

Worse, if you free an object that was allocated with new (instead of using delete), the object’s destructor is not called. If your object uses memory dynamically and the destructor does the clearing up, then what will you have? Yes, a memory leak.

But that won’t happen to you now, because you’ve just read this, right? 😉

Using errno

Lots of functions in the C standard library will set errno to an error code if something goes wrong, so using errno in your programming can help you pinpoint where problems are occurring and what they might be.

errno remains set at the last error code, so bear in mind that:

a) if two subsequent functions are returning errors, you’ll miss the first one if you’re not looking for it, and

b) a function called after one that returns an error does not set errno back to zero (but you can set errno to zero if you like).

How do I use errno?

First of all, include the header in your C program:

#include <errno.h>

Or in your C++ program:

#include <cerrno>

Then, you can access the error code just by using the integer errno.

OK, I’ve got a number from errno, but what does it mean?

All the error codes are defined in the errno.h header file. On Linux this lives somewhere like:

/usr/include/linux/errno.h

Er, isn’t there an easier way to see what’s going wrong?

Well there is, since you ask. You can use strerror to return the actual text error message.

See the example code, and its output below – this will return a nice error message and save you having to rummage through the file looking for an error to match the code you’ve been given. Handy, eh?

Output

Attempting file access...
Something went wrong! errno 13: Permission denied

Source

#include <iostream>
#include <cerrno>
#include <string.h>
#include <stdio.h>
int main()
{
    std::cout << "Attempting file access..." << std::endl;
    FILE *f = fopen("/proc/cpuinfo","w");
    if (f == NULL)   
    {       
        std::cout << "Something went wrong! errno " << errno << ": ";
        std::cout << strerror(errno) << std::endl;
    }
    return 0;
}