Disable code based on existence of Constructor - c++

I am trying to disable some code based on whether the code creates an Object or not (or calls a function or whatever). Sounds a bit strange, I know.
In my library it is possible to create 2 objects, each object needs an interrupt service routine like:
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
The ISR can only be created once but it could be possible that the user just creates one or none of my objects, so the ISR shouldn't be created in the first place to not block the creation of one by the user.
I know it would be easy to encapsulate the code like this
#ifdef OBJECT1
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
#endif
but that forces the user to keep track of the objects she/he created.
Is there an option to let the preprocessor decide if, let's say, the constructor is called once or even existent?
A little bit like something like this
Foo:Foo() {
#define USE_FOO
//Some code
}
#ifdef USE_FOO
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
#endif
EDIT:
Based on the answers i got, I try to clarify my question a bit:
Foo1:Foo1() {
//Some object constructor code
}
Foo2:Foo2() {
//Some object constructor code
}
ISR(TIMER1_COMPA_vect) {
//some interrupt code
}
ISR(TIMER2_COMPA_vect) {
//some interrupt code
}
int main() {
Foo2 foo2;
}
If this is the code we are talking about, the function ISR(TIMER1_COMPA_vect) shouldn't be compiled at all. The ISR MUST be absent.
PS: if you need more information, I can provide more but I tried to keep the problem as basic as possible

Typically what you would do for this type of situation is compile the code for such an object into a library. The linker is smart enough to detect if your main program depends on any function from the library. If it does, it will load the entire compilation unit (i.e. the .c or .cpp file) of that function into your program. Any ISRs that it finds in the compilation unit will be added to your program. If you don't use any functions from the library, the ISRs will not be added.
For example, put something like this in foo1.h:
#pragma once
class Foo1 {
public:
Foo1();
};
Put something like this in foo1.cpp:
#include <foo1.h>
ISR(TIMER1_COMPA_vect) {
}
Foo1::Foo1() {
}
Now you should compile foo1.cpp into foo1.o using avr-gcc. Next, use avr-ar to store foo1.o in an archive named foo1.a. Then, compile your main program with avr-gcc, and provide foo1.a as an argument. Make sure the foo1.a argument comes after main.cpp.

You may need to create a singleton. There are numerous examples. A singleton is a class that constructs itself, once only. The constructors are private and a static method checks a "global" variable to see if the class has already been constructed if not it will construct itself once only. You will may need to consider threading issues although for construction you can simply reference the class early before you have created multiple classes. For multiple users of an interrupt you typically use some sort of dispatcher that the objects register with and then all classes interested in the interrupt are called. The dispatcher may be a singleton. Typically a client of a dispatcher implements an interface. As part of registration with the dispatcher the class tell the dispatcher its "this" pointer and the dispatcher can call the methods implemented from the interface as though they were called as normal. There is no need for the client to have static methods. There are probably patterns for this stuff but I cannot name any.

As you stated your problem sounds strange but if you want to do something only once let's say in the constructor you can go with a simple but very ugly thing like this using local static variable
Foo:Foo() {
static bool init = true;
if( init ) {
//Some code for ISR init
init = false;
}
}
This way your special ISR initialization will take place only once, whatever the number of Foo object you or your user construct
EDIT:
I think there is no way to achieve what you want, at least no clean way.
Imo your problem comes from your ISR macro which actually does two things:
Initializing your ISR vector (ISR registration)
Defining your ISR handler (ISR handler)
To solve your problem I suggest you to split this into two macros then:
ISR registration goes in you Foo1 / Foo2 constructor -> use a global field or whatever mechanism to initialize only once or keep track internally of what has happened or so
Keep another macro ISR_HANDLER with only the handler definition
Your handlers can then remain defined and should have no influence if it is not registered by any of the Foo classes

Related

Is there a way to make global function/static member function callable once?

To clarify, I'm not talking about multi-threaded environment. I often come across a situation where I have to allocate some resources in an init function (and consequently release the resource in a terminate function) and where I would like to avoid calling it twice. I was wondering if there was something like a built-in keyword in C/C++ to make it callable once. Something more sophisticated than a static local variable that I would have duplicated across all my init functions like
static bool isInitialized = false;
if (!isInitialized) {
isInitialized = true;
//...
}
Or maybe it isn't that bad and I could hide this behind a macro CALLABLE_ONCE.
I'm open to any solutions from C/C++03/C++11/C++14.
EDIT:
The reason why I would be using the init/terminate scheme on the global scope would mainly be due to the fact that I tend to create namespaces for entities that shouldn't be instantiated more than once and avoid using singleton as encouraged on this post. Of course using a class would be easier as I would simply use the constructor/destructor, but how can one initialize (only once) this kind of entities(namespaces)?
There is std::call_once, although presented to be used with threads rather than just one thread application, it can be used by a one thread application too.
The one problem you may encounter is if it throws, then it is not considered initialized. You may protect the initialization function with a try/catch if required, though.
Also in your case you may want a public static function and another function that is private. The public static function would perform the std::call_once. Something like this:
class my_class
{
public:
static void init()
{
std::call_once(m_initialized, private_init);
}
private:
static void private_init()
{
... // init here
}
static std::once_flag m_initialized;
};
As you can see, it looks exactly the same as your function, except that the if() and flag switch are hidden. You could also keep the m_initialized flag in your first function as a static variable.
The one difference, though, is that the std::call_once is thread safe.

Compile time check for consecutive functions call

Suppose we have a class like this:
class OProcess {
...
void Process1();
void Process2(); // call only if Process1 wasn't called
...
}
such that function Process2() can be called only when function Process1() has NOT been called already.
Is there a way to check that Process class is used correctly at compile-time? I.e. compiler must give an error if Process1() CAN BE called before Process2() for some instance of OProcess object.
P.S. I understand that there can be code like this:
if (variable == 1000)
Process1();
Process2();
and compiler can't be sure that Process1() will be called before Process2(). But here compiler can be sure that Process1() CAN be called before Process2() for some values of variable. And I need it to make an error or at least warning.
The short answer is Somewhat.
The long answer is: C++ does not implement Linear Typing, thus uniqueness checks cannot be done at compile-time (fully). Still, reading this description gives us a trick: to implement this in the compiler, language designer forbid aliasing and enforce consumption.
So, if you agree that some runtime checks are allowed, then this can be done by having processes consume the object:
class OProcess {
public:
};
std::unique_ptr<OProcessed1> process1(std::unique_ptr<OProcess> op);
std::unique_ptr<OProcess> process2(std::unique_ptr<OProcess> op);
Where OProcessed1 is a proxy over OProcess presenting a restricted interface that exposes only those operations allowed on OProcess after that Process1 was called.
The runtime part of the checks is that:
void func(std::unique_ptr<OProcess> op) {
process1(std::move(op));
process2(std::move(op));
}
will compile, even though it is undefined behavior to do anything other than destruction/assignment to op after moving from it.
The correct way to do it is either make init private and reduce the risk you mention,
or use dependency injection, as 'init' methods, or any logic at all inside the constructor, are bad practice in terms of clean code
Another trick is to have ProcessBase that defines init and calls it in it's constructor. ProcessBase's constructor is called before the derived constructor, thus making sure that init is called before any logic is made in the derived class.
Edit:
You may want to change the logic to have both methods private and have one method called process3() that will call the other methods in the correct order.
Another option is to use the decorator design pattern and wrap one method in a class and have your decorator call them by order.

What are the consequences of having a static pointer to this

I have a class that contains functions that need to run as threads. The proper way to do this (form what I understand) is have these functions declared as static. To use methods from this class I need a to have an instance to that class, so I create a static variable that is initialized to self in the constructor. What are the implications in efficiency and program logic?
class Foo
{
private: Foo* this_instance;
Foo()
{
this_instance=this;
}
void FooBar()
{
...
}
static void* Bar()
{
if (this_instance==NULL) return 1; //throws are not catched are they?
this_instance->FooBar();
return 0;
}
}
Not actual code but to make my question clearer.
The application actually works and I checked it with helgrind/memcheck and the errors are not related to the issue at hand. I'm asking this question because all solutions seem like workarounds, including this one. Others are like the one mentioned by doctor love, other using helper static method.
I am wondering if my approach would result in epic failures at some point in time, for some reason unknown to me and obvious to other more experienced programmers.
You do not need functions to be static to use them in threads. You could bind instance functions or pass the this pointer, or use C++11 with a lambda.
If you use raw threads you will have to catch exceptions in the thread - they will not propagate to the code that started the thread.
In C++11 you can propagate the exceptions, using current_exception and rethrow_exception. See here
EDIT
If you have a static pointer for each type, you can only have one instance of it, yet your code does nothing to prevent the static pointer being reset. Why bother having a class instance in the first place - surely just pass in the parameters? I think it's cleaner to have free functions to do the work. If you think it's not worth the effort, it's your code. What do your co-workers think of your design?

New thread on a class function

I want to make a class that contains a bunch virtual functions which are called on different events. I have the class already but how do I start those functions as new threads? I can manage to do this on global functions only. I want my class to look like this:
class Callbackk{
CallBack(){};
virtual ~Callback(){};
virtual void onSomething();
virtual void onElse(Someclass x);
virtual void onBum(Newclass nc);
}
of course each function would be called with different parameters but the idea is that I want those functions to be void and be able to accept some arguments.
Using: Visual Studio 2010
Different threading mechanisms are using different syntax for this case.
I will supply the example for boost::thread library.
Obviously, you have to bind your function to some class instance for it to be called. This can be accomplished the following way:
// Thread constructor is a template and accepts any object that models 'Callable'
// Note that the thread is automatically started after it's construction.
// So...
// This is the instance of your class, can possibly be some derived
// instance, whatever actually.
Callback* callback_instance;
// This construction would automatically start a new thread running the
// 'onElse' handler with the supplied arguments.
// Note that you may want to make 'x' a member of your thread controlling
// class to make thread suspending and other actions possible.
// You also may want to have something like 'std::vector<boost::thread>' created
// for your case.
boost::thread x(boost::bind(&Callback::onElse, callback_instance, ARGUMENTS));
My suggestion is that you add some static member functions in your class to do so. For example, you could add a static member function called onSomethingThread, which do the same things you want originally by the function onSomething. Then in the function onSomething, you simply create a new thread and run onSomethingThread in it.

OO Programming Question: Global Object

I have probably a quite simple problem but I did not find a proper design decision yet.
Basically, I have 4 different classes and each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this object keeps a socket open to the server throughout program execution. My idea was to have the TCP obejct declared as "global" so that all other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
...
};
class classB
{
private:
public:
classB();
...
};
Unfortunately, when declaring it like this my C++ compiler gives me an error message that some initialized data is written in the executable (???). So I am wondering if there is any other way I could declare this TCP object so that it is available for ALL the other classes and its methods?
Many thanks!
I'd suggest you keep the instance in your initialization code and pass it into each of the classes that needs it. That way, it's much easier to substitute a mock implementation for testing.
This sounds like a job for the Singleton design pattern.
The me sounds more for the right time to use Dependency Injection as i tend to avoid Singleton as much as i can (Singleton are just another way for accessing GLOBLAS, and its something to be avoided)
Singleton vs Dependency Injection has been already discussed on SO, check the "dependency injection" tag (sorry for not posting some links, but SO doens't allow me to post more than one link being a new user)
Wikipedia: Dependency Injection
As per your current code example, should be modified to allow injecting the Socket on the constructor of each Class:
class classA
{
private:
public:
classA(TCPSocket socket);
...
};
class classB
{
private:
public:
classB(TCPSocket socket);
...
};
Pass the socket into the constructor of each object. Then create a separate factory class which creates them and passes in the appropriate socket. All code uses the set of objects which are required to have the same socket should then create them via an instance of this factory object. This decouples the classes that should be using the single socket while still allowing the enforcement of the shared socket rule.
The best way to go about doing this is with a Singleton. Here is it's implementation in Java
Singleton Class:
public class SingletonTCPSocket {
private SingletonTCPSocket() {
// Private Constructor
}
private static class SingletonTCPSocketHolder {
private static final SingletonTCPSocket INSTANCE = new SingletonTCPSocket ();
}
public static SingletonTCPSocket getInstance() {
return SingletonTCPSocket.INSTANCE;
}
// Your Socket Specific Code Here
private TCPSocket mySocket;
public void OpenSocket();
}
The class that needs the socket:
public class ClassA {
public ClassA {
SingletonTCPSocket.getInstance().OpenSocket();
}
}
When you have an object which is unique in your program and used in a lot of places, you have several options:
pass a reference to the object everywhere
use a global more or less well hidden (singleton, mono-state, ...)
Each approach have its drawbacks. They are quite well commented and some have very strong opinions on those issues (do a search for "singleton anti-pattern"). I'll just give some of those, and not try to be complete.
passing a reference along is tedious and clutter the code; so you end up by keeping these references in some long lived object as well to reduce the number of parameters. When the time comes where the "unique" object is no more unique, you are ready? No: you have several paths to the unique object and you'll see that they now refer to different objects, and that they are used inconsistently. Debugging this can be a nightmare worse than modifying the code from a global approach to a passed along approach, and worse had not be planned in the schedules as the code was ready.
global like approach problem are even more well known. They introduce hidden dependencies (so reusing components is more difficult), unexpected side-effect (getting the right behaviour is more difficult, fixing a bug somewhere triggers a bug in another components), testing is more complicated, ...
In your case, having a socket is not something intrinsically unique. The possibility of having to use another one in your program or to reuse the components somewhere were that socket is no more unique seems quite high. I'd not go for a global approach but a parametrized one. Note that if your socket is intrinsically unique -- says it is for over the network logging -- you'd better encapsulate it in a object designed for that purpose. Logging for instance. And then it could make sense to use a global like feature.
As everyone has mentioned, globals are bad etc.
But to actually address the compile error that you have, I'm pretty sure it's because you're defining the global in a header file, which is being included in multiple files. What you want is this:
something.h
extern classTCP TCPSocket; //global is DECLARED here
class classA
{
private:
public:
classA();
...
};
something.cpp
classTCP TCPSocket; //global is DEFINED here