Boost logo

Boost :

From: Mateusz Loskot (mateusz_at_[hidden])
Date: 2020-01-19 11:41:19


On Sun, 19 Jan 2020 at 11:57, anshu khare via Boost
<boost_at_[hidden]> wrote:
> But when I run
>
> const std::string i = {};
> boost::optional<const std::string&> str = i;
> cout << get_optional_value_or(str, "some other string") ;
>
> The output is an empty string.
> Shouldn't it give "some other string as output"

No, it should not.

>From the documentation:
"Class template optional is a wrapper for representing 'optional' (or
'nullable')
objects who may not (yet) contain a valid value."

An empty string in `i` variable IS a valid value, so `str` is set with
a valid value,
Since it is valid value, get_optional_value_or returns that valid value
and not the "some other string".

> because if I run the same
> code with integer it gives the second parameter of get_optional_value_or()
> as output?

Are you sure?

This is expected to print 0, the valid value of `i` and not the default 1:

int i = {};
boost::optional<int> v = i;
cout << get_optional_value_or(v, 1);

Best regards,

-- 
Mateusz Loskot, http://mateusz.loskot.net

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk