0

This is a very fundamental question. Is there any benefit in using boost::optional in the following scenario:

int somefunction(boost::optional<const Param&> value = getDefaultParam()){
    return value->dosomething();
}

or

int somefunction(boost::optional<const Param&> value){
    if (!value) 
            value = getDefaultParam();
    return value->dosomething();
}

as opposed to just doing this:

int somefunction(const Param& value = getDefaultParam()){
    return value.dosomething();
}

This is for the specific case where I know that I am initializing the Param object to a default value. Can there be any benefit of using a boost::optional on Param to the API or the client of the API ?

SkypeMeSM
  • 3,197
  • 8
  • 43
  • 61
  • 2
    No. Just do the last one. – metal Mar 17 '15 at 19:40
  • 1
    What does `getDefaultParam` return? If it returns a `Param`, #2 is not going to be very correct (I am unsure if `boost` would let it compile, but it won't work). Generally a `boost::optional` can be replaced with a `Param const*`, as `boost::optional` is a non-owning reseatable nullable reference... and so is `Param const*`. – Yakk - Adam Nevraumont Mar 17 '15 at 19:55

1 Answers1

3

First off, this is bad:

int somefunction(boost::optional<const Param&> value = getDefaultParam()){
    return value->dosomething();
}

someFunction could be called with boost::none, in which case attempting to access it's value will throw an exception.

Second, if you have a boost::optional<const Param&>, an API is provided to get its value or a default:

boost::optional<const Param&> value = ...;
value.value_or(getDefaultParam()).doSomething();

EDIT: On this simple case, it may not be worth bringing in optional. If you do something like this:

int someFunc(const Param& value = getDefaultParam())
{
    return value.doSomething();
}

// Elsewhere...
int x = someCondition ? someFunc(abc) : someFunc();

There isn't really a point for optional here. Of course, something simple like this, there may not be much need for someFunc either:

int x = (someCondition ? abc : getDefaultParam()).doSomething();

However, if you need longer-term storage/tracking of whether a value is available or not, then boost::optional might be appropriate.

Matthew Moss
  • 1,258
  • 7
  • 16