Boost C++ Libraries

...one 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.
PrevUpHomeNext

Bypassing unnecessary default construction

Suppose we have class Date, which does not have a default constructor: there is no good candidate for a default date. We have a function that returns two dates in form of a boost::tuple:

boost::tuple<Date, Date> getPeriod();

In other place we want to use the result of getPeriod, but want the two dates to be named: begin and end. We want to implement something like 'multiple return values':

Date begin, end; // Error: no default ctor!
boost::tie(begin, end) = getPeriod();

The second line works already, this is the capability of Boost.Tuple library, but the first line won't work. We could set some invented initial dates, but it is confusing and may be an unacceptable cost, given that these values will be overwritten in the next line anyway. This is where optional can help:

boost::optional<Date> begin, end;
boost::tie(begin, end) = getPeriod();

It works because inside boost::tie a move-assignment from T is invoked on optional<T>, which internally calls a move-constructor of T.


PrevUpHomeNext