Given that all else is equal, and there are no coding standards defining the bes
ID: 655059 • Letter: G
Question
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?
For example, something like one of these declarations:
bool getMethod(double& ret);
double getMethod(bool& ok);
void getMethod(bool& ok, double& ret);
pair<bool, double> getMethod();
bool checkMethod(); // eg if (checkMethod())
double getMethod(); // result = getMethod();
or something else, like return a struct
The value may exist about 50% of the time.
The existing code already does a lot of the last method, i.e. using a checkMethod() but I was wondering if that's really an efficient way to do it - via two calls (half the time).
Explanation / Answer
Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?
Starting from C++14, you can use std::optional. (until then, you can use boost::optional).
The class behaves like a pointer, but allocates no dynamic memory and expresses explicitly the fact that the value can be missing:
The following code snippets perform the same function:
bool getMethod(double& ret); // from your code
// client code:
double result = 0.;
if(getMethod(result)) {
// result has a valid value
}
and:
#include <optional>
std::optional<double> getMethod();
if(auto result = getMethod()) {
// *result is a valid value
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.