Using boost::optional can be an advantage in certain situation. In C++ it effectively works by being able to turn any datatype into a nullable value. It works much the same way as returning a null pointer to an object but without using a pointer. Instead this will work by being able to return an object which may or may not valid.

It is typically used to return a value from a function where the function may fail in certain situations. If you attempt to use the optional value which has not been set it will fail and the program will abort. This of course is also useful for debugging in order to catch issues sooner rather than later by accessing various variable that may not have valid values.

It can of course also be used to pass optional parameters to functions where you may not want to use operator overloading.

Here is an example of it converting an string to an int which will obviously fail on one of the strings.

#include <stdio.h>
#include <string>

#include <boost/optional.hpp>

boost::optional<int> func(const std::string &str)
        boost::optional<int> value;
        int tmp = 0;

        if (sscanf(str.c_str(), "%d", &tmp) == 1)

        return value;

int main(int argc, char **argv)
        boost::optional<int> v1 = func("31245");
        boost::optional<int> v2 = func("hello");

        if (v1)
                printf("%d\n", v1.get());
                printf("v1 not valid\n");

        if (v2)
                printf("%d\n", v2.get());
                printf("v2 not valid\n");

        return 0;

Did You find this page useful?

Yes No

Last Modified: 14 December 2016

Releated Posts

2017-04-25 - Linux Programming - Signals the easy way
2017-03-01 - Shooting yourself in the head with threads
2013-08-22 - CPP - Prevent an object by being copied with boost::noncopyable
2013-03-29 - CPP - Why you need a copy constructor
2013-03-27 - CPP -boost::optional
2012-11-06 - C++ - Stringstream example
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-06-30 - CPP - Creating A basic python wrapper
2012-06-16 - CPP - Using gperf
2012-05-10 - CPP - Optional function arguments
2012-03-19 - CPP - Read / Write std::map to a file.