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 within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You can use local static variable:
Compact version using lambda function:
Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.
Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:
This makes it easy to convert into a general-purpose macro:
Which can be placed anywhere you want call-by-need:
And for good measure, atomics shorten the expression and make it thread-safe:
Use global static objects with constructors (which are called before
main
)? Or just inside a routineThere are very few cases when this is not fast enough!
addenda
In multithreaded context this might not be enough:
You may also be interested in pthread_once or
constructor
function__attribute__
of GCC.With C++11, you may want std::call_once.
You may want to use
<atomic>
and perhaps declarestatic volatile std::atomic_bool initialized;
(but you need to be careful) if your function can be called from several threads.But these might not be available on your system; they are available on Linux!
could you do this
have a function that return a bool or some datatype called init
I made it happen this way, you need static bool to make it happens
Using C++11 -- use the
std::call_once