最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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;
}
发布评论

评论列表(0)

  1. 暂无评论