Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.


Fernando Luis Cacciola Carballal

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at

Table of Contents

Quick Start
Optional return values
Optional automatic variables
Optional data members
Bypassing unnecessary default construction
Storage in containers
Design Overview
When to use Optional
Relational operators
IO operators
Optional references
In-Place Factories
Exception Safety Guarantees
Type requirements
Performance considerations
Header <boost/none.hpp>
Header <boost/optional/bad_optional_access.hpp>
Header <boost/optional/optional_io.hpp>
Header <boost/optional/optional_fwd.hpp>
Header <boost/optional/optional.hpp>
Header <boost/optional.hpp>
Dependencies and Portability
Emplace operations in older compilers
Optional Reference Binding
Release Notes

Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers. This is a header-only library.


Suppose we want to read a parameter form a config file which represents some integral value, let's call it "MaxValue". It is possible that this parameter is not specified; such situation is no error. It is valid to not specify the parameter and in that case the program is supposed to behave slightly differently. Also, suppose that any possible value of type int is a valid value for "MaxValue", so we cannot just use -1 to represent the absence of the parameter in the config file.


This is how you solve it with boost::optional:

#include <boost/optional.hpp>

boost::optional<int> getConfigParam(std::string name);  // return either an int or a `not-an-int`

int main()
  if (boost::optional<int> oi = getConfigParam("MaxValue")) // did I get a real int?
    runWithMax(*oi);                                        // use my int

Last revised: December 05, 2017 at 23:58:27 GMT