How to execute a piece of code only once?

后端 未结 8 843
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:35

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code wi

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 05:06

    As of C++11, static local variables are thread-safe and usually sufficient for most cases, so std::call_once() et al. very well may be overkill.

    This looks especially elegant when using C++17's initialisation-within-if and std::exchange():

    #include 
    
    void
    do_something_expensive_once()
    {
        if ( static auto called = false; !std::exchange(called, true) ) {
            do_something_expensive();
        }
    }
    

    If this is a pattern you use a lot, then we can encapsulate it via a tag type:

    #include 
    #include 
    
    template 
    auto
    call_once()
    {
        static auto called = false;
        return !std::exchange(called, true);
    }
    
    void
    do_something_expensive()
    {
        std::cout << "something expensive\n";
    }
    
    void
    do_something_expensive_once()
    {
        if ( call_once() ) {
            do_something_expensive();
        }
    }
    
    auto
    main() -> int
    {
        for (auto i = 0; i < 5; ++i) {
            do_something_expensive_once();
        }
    
        return 0;
    }
    

    This will only print something expensive a single time. Result! It also uses the ability to declare a tag struct in a template argument list, for maximal brevity.

    Alternatively, you could template on a function's address, a unique integer, etc.

    You can then also pass a callable to call_once(), and so on, and so forth. As usual for C++: the possibilities are endless!

提交回复
热议问题