I'm new to C++. I have a code similar to this:
//static
absl::optional<bool> someFunc() {
if(absl::getFlag(FLAG_is_real) < absl::now())
// do something...
return true;
}
//static
absl::optional<bool> someOtherFunc() {
if(absl::getFlag(FLAG_is_real) > absl::now())
// do something...
return true;
}
I don't want to call absl::getFlag()
twice, as it is expensive. But I couldn't declare it as a global variable either, as the flag value type is absl::Duration
and it is not trivially destructible.
What is the best way to reuse the flag value in both methods without having to call absl::getFlag()
twice?
I'm new to C++. I have a code similar to this:
//static
absl::optional<bool> someFunc() {
if(absl::getFlag(FLAG_is_real) < absl::now())
// do something...
return true;
}
//static
absl::optional<bool> someOtherFunc() {
if(absl::getFlag(FLAG_is_real) > absl::now())
// do something...
return true;
}
I don't want to call absl::getFlag()
twice, as it is expensive. But I couldn't declare it as a global variable either, as the flag value type is absl::Duration
and it is not trivially destructible.
What is the best way to reuse the flag value in both methods without having to call absl::getFlag()
twice?
1 Answer
Reset to default 2If the value of absl::getFlag(FLAG_is_real)
doesn't change over time, then simply store it in a static
variable that is initialized the first time it's used, eg:
// static
absl::Duration getDuration() {
static absl::Duration duration = absl::getFlag(FLAG_is_real);
return duration;
}
// static
absl::optional<bool> someFunc() {
if (getDuration() < absl::now())
// do something...
return true;
}
// static
absl::optional<bool> someOtherFunc() {
if (getDuration() > absl::now())
// do something...
return true;
}
I couldn't declaring it as global variable either as the flat value type is absl::Duration and it is not trivially destructible
global objects in C++ can have a non-trivial destructor. – Ahmed AEK Commented Mar 24 at 22:28