質問

I am reviewing some production code where a function says it will return a boost::optional, but it just returns a double: e.g.

boost::optional<double> Foo(){
   double a = 1.0;
   double b = 2.0;
   return a + b;
}

Is this acceptable style/are there any cases where this is unsafe?

役に立ちましたか?

解決

This is the style I like to use. The returned double will be implicitly converted to a boost::optional which has been set and contains the value of that double. I can't think of any case where this is unsafe. EDIT: There are caveats when the type held by optional<> is bool - see the docs.

This conversion will use this boost::optional constructor:

boost::optional ( T const& v )

where T in this case is double. Note that this constructor is not explicit, and that's been designed precisely to allow the code in your example!

If, elsewhere, the function needs to return an optional object which has not been set, return boost::optional().

References:

http://en.cppreference.com/w/cpp/language/implicit_cast - See bullet 3 about return values.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top