Search code examples
c++boostboost-optional

Benefit from using boost::optional in the following usecase?


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 ?


Solution

  • 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.