c++ - What is the best practice to use flag in multiple methods inside a class? - Stack Overflow

I'm new to C++. I have a code similar to this:staticabsl::optional<bool> someFunc() {if(

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?

Share Improve this question edited Mar 24 at 22:37 Remy Lebeau 601k36 gold badges507 silver badges851 bronze badges asked Mar 24 at 22:15 AdershAdersh 1191 silver badge10 bronze badges 4
  • Updated the example – Adersh Commented Mar 24 at 22:26
  • 1 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
  • one with non trivial destructors are not advised so I am getting pushback not to use it – Adersh Commented Mar 24 at 22:31
  • 2 just pass it into both functions as an argument – Ahmed AEK Commented Mar 24 at 23:01
Add a comment  | 

1 Answer 1

Reset to default 2

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744226104a4564011.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信