(Assuming a single-threaded environment)
A function that fulfills this criterion is:
bool MyClass::is_initialized = false;
void MyClass::lazy_initialize()
{
if (!is_initialized)
{
initialize(); //Should not be called multiple times
is_initialized = true;
}
}
In essence, I can call this function multiple times and not worry about it initializing MyClass
multiple times
A function that does not fulfill this criterion might be:
Foo* MyClass::ptr = NULL;
void initialize()
{
ptr = new Foo();
}
Calling initialize()
multiple times will cause a memory leak
Motivation
It would be nice to have a single concise word to describe this behavior so that functions that are expected to meet this criterion can be duly commented (especially useful when describing interface functions that are expected to be overridden)
Best Answer
This type of function / operation is called Idempotent
In mathematics, this means that if f is idempotent, f(f(x)) = f(x), which is the same as saying f∘f = f.
In computer science, this means that if
f(x);
is idempotent,f(x);
is the same asf(x); f(x);
.Note: These meanings seem different, but under the denotational semantics of state, the word "idempotent" actually has the same exact meaning in both mathematics and computer science.