문제

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