Function Call Guard - c++

Suppose I have a free function called InitFoo. I'd like to protect this function from being called multiple times by accident. Without much thought I wrote the following:
void InitFoo()
{
{
static bool flag = false;
if(flag) return;
flag = true;
}
//Actual code goes here.
}
This looks like a big wart, though. InitFoo does not need to preserve any other state information. Can someone suggest a way to accomplish the same goal without the ugliness?
Macros don't count, of course.

You can do it with some different ugliness:
struct InitFoo
{
InitFoo()
{
// one-time code goes here
}
};
void Foo()
{
static InitFoo i;
}
You're still using static, but now you don't need to do your own flag checking - static already puts in a flag and a check for it, so it only constructs i once.

Well, a constructor is only automatically called once. If you create a single instance of this class:
class Foo
{
public:
Foo(void)
{
// do stuff
}
}
Then //do stuff will only execute once. The only way to execute it twice is to create another instance of the class.
You can prevent this by using a Singleton. In effect, //do stuff can only possibly be called once.

I'd like to protect this function from being called multiple times by accident
To me, this sounds like an issue that will only come up during debugging. If that is the case, I would simply do the following:
void InitFoo()
{
#ifndef NDEBUG
static bool onlyCalledOnce = TRUE;
assert(onlyCalledOnce);
onlyCalledOnce = FALSE;
#endif
...
}
The purpose of this particular wart is easily discerned just by looking at it, and it will cause a nice, big, flashy assertion failure if a programmer ever makes the mistake of calling InitFoo more than once. It will also completely dissapear in production code. (when NDEBUG is defined).
edit: A quick note on motivation:
Calling an init function more than once is probably a big error. If the end user of this function has mistakenly called it twice, quietly ignoring that mistake is probably not the way to go. If you do not go the assert() route, I would recommend at least dumping a message out to stdout or stderr.

That is exactly how I'd do it. You could use some function pointer shuffling if you want an alternative:
static void InitFoo_impl()
{
// Do stuff.
// Next time InitFoo is called, call abort() instead.
InitFoo = &abort;
}
void (*InitFoo)() = &InitFoo_impl;

Do you also need it to be multi-thread safe? Look into the Singleton pattern with double-check locking (which is surprising easy to get wrong).
If you don't want a whole class for this, another simple way is:
In a .cpp (don't declare InitBlah in the .h)
// don't call this -- called by blahInited initialization
static bool InitBlah()
{
// init stuff here
return true;
}
bool blahInited = InitBlah();
No one can call it outside of this .cpp, and it gets called. Sure, someone could call it in this .cpp -- depends on how much you care that it's impossible vs. inconvenient and documented.
If you care about order or doing it at a specific time, then Singleton is probably for you.

I do exactly that all the time with situations that need that one-time-only-but-not-worth-making-a-whole-class-for. Of course, it assumes you don't worry about thread-related issues. I usually prefix the variable name with "s_" to make it clear that it's a static variable.

Hmmm... if you don't object to using Boost, then have a look at boost::call_once:
namespace { boost::once_flag foo_init_flag = BOOST_ONCE_INIT; }
void InitFoo() {
// do stuff here
}
void FooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
void AnotherFooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}

Not that I am very excited about it, but this is just another way: function object.
#import <iostream>
class CallOnce {
private:
bool called;
public:
CallOnce() {
called = false;
}
void operator()(void) {
if (called) {
std::cout << "too many times, pal" <<std::endl;
return;
}
std::cout << "I was called!" << std::endl;
called = true;
}
};
int main(void) {
CallOnce call;
call();
call();
}

Related

Name of pattern / well written?

I have the following code:
Doc header file
class CMyDoc
{
public:
class Suspender
{
friend class CMyDoc;
static bool m_suspending;
inline static const bool IsSuspending() { return m_suspending; }
public:
Suspender()
{
m_suspending = true;
}
~Suspender()
{
m_suspending = false;
}
};
}
Doc source file
Static variable initialization:
bool CMyDoc::Suspender::m_suspending = false;
Check if it is on the "not allowed" to do things state, and if so, don't do them:
void CMyDoc::SomeMethod()
{
if (!Suspender::IsSuspending())
DoThings();
}
Somewhere where I want to run some code on the "not allowed" state
Declare a variable of the Suspender type. Automatically will put on the "not allowed state" on the declaration. But the greatest benefit is it will return itself back to the "allowed" state when the stack frame ends, as it passes on the s variable's destructor.
void CMyView::DoSomething()
{
CMyDoc::Suspender s;
((CMyDoc*) GetDocument())->SomeMethod();
}
QUESTIONS:
What is the name of the pattern?
Am I doing it in the most correct way? Can I avoid to have a static variable?
No, I don't think you are doing it in the most correct way, and because of the flaw in it I don't think its really RAII either.
The flaw I believe is there can be demonstrated without threads.
void SomeViewMethod()
{
Suspender s1;
((CMyDoc*) GetDocument())->SomeMethod();
}
SomeOtherViewMethod()
{
Suspender s2;
((CMyDoc*) GetDocument())->SomeMethod();
SomeViewMethod();
// this looks like suspender s2 should be suspending the next call...
// but when the s1 inside SomeViewMethod went out of scope it turned off suspending
((CMyDoc*) GetDocument())->SomeMethod();
}
This particular issue could be addressed by replacing the bool with an int to allow nested suspension. The int would be incremented by each suspender and suspension would be off if the value = 0.
(In the past I have successfully used such a pattern to control repetitive redraws)
1.) m_suspending is a property of CMyDoc because its behavior depends on it. Therefore it should be a member variable of CMyDoc.
2.) If Suspender can be created within multiple threads then m_suspending should be synchronized. And global variables are bad anyway.
3.) RAII is the keyword and your example looks similar to the way how mutex and lock_guard interact.
4.) You do not need a name for every trivial "pattern". RAII is fundamental in C++.

In c++, is there a way to jump from one function to another

In C++ can i jump from inside A() to B() without A() in call stack? Is there anything like goto for this case? My situation is I should destroy an object at the end of one of its function.
class timeBomb{
public:
void detonate(int time){
sleep(time);
goto this->blast(this); //something like that
};
timeBomb();
static void blast(timeBomb bomb){
delete bomb;
}
}
int main(){
timeBomb *myBomb = new timeBomb();
myBomb->detonate(2);
return 0;
}
I could have gone away with delete this;. but in my code on a specific condition the constructor itself has to call a function which in turn call a function like detonate.
to solve my problem i could have asked can i abort creating an object. but i found jumping form one function to another avoiding parent function in call stack fascinating and useful.
You can "go back in time" to a place where you've been before using setjmp and longjmp, but there is nothing to jump to a random new location in the code (aside from various system dependent things, like using inline assembler or some such - and this would still be hard to make very generic, as you need to care for stack cleanup and other things like that).
If you have common functionality then make a (private) method and call it from all methods that need that functionality:
class timeBomb {
public:
void detonate(int time){
sleep(time);
blast();
};
timeBomb();
private:
void blast(){
delete this; // Very dangerous!
}
};

In a C++ class, what's the difference between accessing a member variable with "this"

I made a simple class to represent a door. To return the variables, I'm accessing them with the this pointer. With respect to just accessing variables, what's the difference between accessing them with the this pointer and without?
class Door
{
protected:
bool shut; // true if shut, false if not shut
public:
Door(); // Constructs a shut door.
bool isOpen(); // Is the door open?
void Open(); // Opens the door, if possible. By default it
// is always possible to open a generic door.
void Close(); // Shuts the door.
};
Door::Door()
{}
bool Door::isOpen()
{
return this->shut;
}
void Door::Open()
{
this->shut = false;
}
void Door::Close()
{
if(this->isOpen()) this->shut = true;
}
There may or may not be a difference here, but what about for more complex classes?
Nothing. The this pointer is automatically added if you exclude it.
You only have to use it if you're doing something like this:
void Door::foo(bool shut)
{
this->shut = shut; // this is used to avoid ambiguity
}
More usages
A brief overview:
Think of methods as functions that pass a pointer as their first argument.
void Door::foo(int x) { this->y = x; } // this keyword not needed
is roughly equivilent to
void foo(Door* this_ptr, int x) { this_ptr->y = x; }
Methods just automate this.
There's no difference.
When you write sane C++, you shouldn't have to say this at all except in very specific situations. (The only ones I can think of are binding pointers-to-member-function, passing the instance pointer to some other object, and some situations involving templates and inheritance (thanks to Mooing Duck for that last example).)
Just give your function arguments and local variables and member variables sensible names so that you don't get any ambiguities.
There's a slew of more recent quasi-object-oriented languages which have made the words "this" and "new" all but synonymous with "I'm using objects" for younger generations, but that is not the C++ idiom.
In your case there is no difference.
Only more typing work.
This whole thing seems to be an exercise in superfluous typing. As far as I can see, Close can be condensed down to:
void Door::Close() {
shut = true;
}
Doing the assignment even when it's unnecessary is much simpler than testing and setting only if it's currently false.
It's also worth mentioning (IMO) that this comment:
Door(); // Constructs a shut door.
Does not seem to fit with the implementation:
Door::Door()
{}
If you want the default ctor to initialize shut to true, you need/want to add some code to do that.
Worse, your IsOpen seems to get things exactly backward:
bool Door::isOpen()
{
return this->shut;
}
If it's shut it's not open, and vice versa.
There are no difference, except more type and the noise introduced by this->.
void Door::Close()
{
if(isOpen()) shut = true;
}
is more readable them this :
void Door::Close()
{
if(this->isOpen()) this->shut = true;
}
but that's only personal preference, and a matter of a style.

C++ - basic function question

Is there any way to make a function call only once?
Suppose I have some class
struct A {
void MainRoutine(Params) {
// Want to call other routine only once
}
void OtherRoutine(Params) {
// Do something that should be done only once and
// what depends on the params
}
};
I want to call OtherRoutine only once in MainRoutine (I assume that MainRoutine is going to be called N times. I can't call OtherRoutine from the constructor, because it accepts Params which may not be available at the time when object is being constructed.
Basically I want to do something like
static bool called = false;
if (!called) {
OtherRoutine(Params);
called = true;
}
but I hope there is a more "beautiful" way of doing this... (which could be written in one line)
Maybe something using boost::function or some part of boost that I don't know about? :)
Thank you
Take a look at Boost Thread's one-time initialization mechanism
You can also put the call-only-once logic, which you already outlined, inside OtherRoutine, causing it to return early if it has already been executed before.
Logically, its pretty much the same. Stylistically, it might be nicer.
You were definitely on the right track already. You should put your static 'called' variable inside your struct... ahem: you should make it a class instead, make it private, and make sure the state of the static variable is queried inside of OtherRoutine. You should not make it more complicated than it needs to be. Using boost, or anything else for so simple a mechanism is just overkill.
You could achieve this with boost::function and bind. Assuming you want OtherRoutine only to be called once per object,
struct A {
A() {
Routine = boost::bind(&A::OtherRoutine, this);
}
boost::function<void()> Routine;
private:
void MainRoutine() {
// Do stuff that should occur on every call
}
void OtherRoutine() {
Routine = boost::bind(&A::MainRoutine, this);
// Do stuff that should only occur once
MainRoutine();
}
};
A foo;
foo.Routine(); // OtherRoutine is called
foo.Routine(); // Now all subsequent calls will go to MainRoutine
foo.Routine();
I would suggest doing what the other people have said, though. While this may look 'cleaner,' it's overly complicated when compared to the alternatives.
Another way that verges on "cute" would be to have a static object and call your function from within its constructor. Something like...
struct OneShotOtherRoutine
{
OneShotOtherRoutine(A a, Params params)
{
a.OtherRoutine(params);
}
};
struct A
{
friend struct OneShotOtherRoutine;
public:
void MainRoutine(Params params)
{
static OneShotOtherRoutine(params);
// Main Routine code
}
private:
void OtherRoutine(Params params)
{
// Other routine code
}
};
You'd have to split things up so that each implementation could see the other struct's declaration, but this could do what you want, assuming it's acceptable that OtherRoutine gets called when statics are initialized.

Static vs. member variable

For debugging, I would like to add some counter variables to my class. But it would be nice to do it without changing the header to cause much recompiling.
If Ive understood the keyword correctly, the following two snippets would be quite identical. Assuming of course that there is only one instance.
class FooA
{
public:
FooA() : count(0) {}
~FooA() {}
void update()
{
++count;
}
private:
int count;
};
vs.
class FooB
{
public:
FooB() {}
~FooB() {}
void update()
{
static int count = 0;
++count;
}
};
In FooA, count can be accessed anywhere within the class, and also bloats the header, as the variable should be removed when not needed anymore.
In FooB, the variable is only visible within the one function where it exists. Easy to remove later. The only drawback I can think of is the fact that FooB's count is shared among all instances of the class, but thats not a problem in my case.
Is this correct use of the keyword? I assume that once count is created in FooB, it stays created and is not re-initialized to zero every call to update.
Are there any other caveats or headsup I should be aware of?
Edit: After being notified that this would cause problems in multithreaded environments, I clarify that my codebase is singlethreaded.
Your assumptions about static function variables are correct. If you access this from multiple threads, it may not be correct. Consider using InterlockedIncrement().
What you really want, for your long term C++ toolbox is a threadsafe, general purpose debug counters class that allows you to drop it in anywhere and use it, and be accessible from anywhere else to print it. If your code is performance sensitive, you probably want it to automatically do nothing in non-debug builds.
The interface for such a class would probably look like:
class Counters {
public:
// Counters singleton request pattern.
// Counters::get()["my-counter"]++;
static Counters& get() {
if (!_counters) _counters = new Counters();
}
// Bad idea if you want to deal with multithreaded things.
// If you do, either provide an Increment(int inc_by); function instead of this,
// or return some sort of atomic counter instead of an int.
int& operator[](const string& key) {
if (__DEBUG__) {
return _counter_map.operator[](key);
} else {
return _bogus;
}
}
// you have to deal with exposing iteration support.
private:
Counters() {}
// Kill copy and operator=
void Counters(const Counters&);
Counters& operator=(const Counters&);
// Singleton member.
static Counters* _counters;
// Map to store the counters.
std::map<string, int> _counter_map;
// Bogus counter for opt builds.
int _bogus;
};
Once you have this, you can drop it in at will wherever you want in your .cpp file by calling:
void Foo::update() {
// Leave this in permanently, it will automatically get killed in OPT.
Counters::get()["update-counter"]++;
}
And in your main, if you have built in iteration support, you do:
int main(...) {
...
for (Counters::const_iterator i = Counters::get().begin(); i != Countes::get().end(); ++i) {
cout << i.first << ": " << i.second;
}
...
}
Creating the counters class is somewhat heavy weight, but if you are doing a bunch of cpp coding, you may find it useful to write once and then be able to just link it in as part of any lib.
The major problems with static variables occur when they are used together with multi-threading. If your app is single-threaded, what you are doing is quite correct.
What I usually do in this situation is to put count in a anonymous namespace in the source file for the class. This means that you can add/remove the variable at will, it can can used anywhere in the file, and there is no chance of a name conflict. It does have the drawback that it can only be used in functions in the source file, not inlined functions in the header file, but I think that is what you want.
In file FooC.cpp
namespace {
int count=0;
}
void FooC::update()
{
++count;
}