Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure a function is only called once

Tags:

c++

Suppose I have a function named caller, which will call a function named callee:

void caller() {     callee(); }   

Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:

void caller() {     static bool bFirst = true;     if(bFirst)     {         callee();         bFirst = false;     } } 

My opinion for this is it needs more code, and it needs one more check in every call of function caller.
A better solution to me is as follow: (suppose callee returns int)

void caller() {     static int ret = callee(); }   

But this can't handle the case if callee returns void, my solution is using the comma expression:

void caller() {     static int ret = (callee(), 1); }   

But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.

Do you have any good idea to make sure a function is only called once?

like image 332
Baiyan Huang Avatar asked Nov 13 '10 16:11

Baiyan Huang


People also ask

How do you make a function only called once?

var something = (function() { var executed = false; return function(value) { // if an argument is not present then if(arguments. length == 0) { if (! executed) { executed = true; //Do stuff here only once unless reset console.

Can a function only be used once?

It's fine to have a function even if only used once. Blocks of code should ideally only do one thing, perform one computation, one calculation. This makes it easy to work on the flow of your logic, instead of getting bogged down with huge blocks of code.

Can a function be called multiple times?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.


1 Answers

You could use this:

void caller() {     static class Once { public: Once(){callee();}} Once_; } 
like image 136
wimh Avatar answered Oct 07 '22 06:10

wimh