c++abseil

What is the best practice to use flag in multiple methods inside a class?


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?


Solution

  • If 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;
    }