Call function once across multiple instances of a class - c++

I have been looking around for a while now and can't seem to find an answer to this.
So, if I have several instances of a class, how can I call a function only once from all instances of that class?
For example, if I have a function called myFunc() within a class called myClass and two instances of that class called class1 and class2, then
class1.myFunc() should return 1,
class2.myFunc() should return 0, and
class1.myFunc() should return 0.
How would I do this?
class myClass{
public:
myClass(){}
int myFunc(){
if (myFuncHasBeenCalled){
return 0;
}
else{
return 1;
}
}
}
myClass class1;
myClass class2;
class1.myFunc(); //would output 1
class2.myFunc(); //would output 0
class1.myFunc(); //would output 0

You can achieve that by
introducing a class variable, using static keyword for it in class declaration
define the class variable in a (separate) code file, with initialisation
check it inside the function, if 0 output 1 else 0
increase (or set to non-zero) afterwards
be careful, using synchronisation mechanisms, in case the calls might be from different contexts/threads/tasks/processes (whatever is applicable in your environment)
(If you show your attempts with static variables and explain the problems you had, this could become more detailed.)

You have several options available: the idea is that you need to have some value that can be accessed independently of the instances of the class. static is the way to do this in all cases (except when it's not).
Option one is best option -- static variable in member functions
The approach I would recommend is using a static variable in the member function; this avoids polluting the class itself and makes it easier for you to maintain a consistent ABI as well as a consistent API, across updates. It is very easy to reason about your code as you're not allowing anything else to access the variable.
Example:
struct S {
int F() const {
static int n = 1;
if (n == 1) {
n = 0;
return 1;
}
return n;
}
};
Option two is bad option -- static variable in class
An alternative, which seems to be popular, is to keep a static member variable. This allows you do to the same thing as the previous example, but makes it harder to maintain the API and the ABI across upgrades. It also makes it harder to reason about your code and makes it easier to introduce bugs -- a static member variable is not much different from a global variable.
Example:
struct S {
static int n;
int F() const {
if (n == 1) {
n = 0;
return 1;
}
return n;
}
};
int S::n = 1;
Option three is worst option -- global variables
The worst alternative is to use a global variable. I'm not going to give you an example of this -- don't do it. If you must do it anyway (you don't), declare your variables in an anonymous namespace in your .cpp file.
namespace {
int n = 0
}
Options four -- good option
Another approach is to use a static member function. This functions is fully independent of all instance of the class. The only difference in the implementation is that you add static to the function declaration -- otherwise, you can use the first two options. This won't be possible in all situations though.
Caveats and other notes
If you need to use the variable to communicate state between two functions, you have to use one of the global options and cannot use a static variable in a member function.
In all cases, if you're not modifying the instance, you should mark your functions const.
You should really use std::atomic variables
You should use some sort of mechanism that guarantees that your code is threadsafe.

Related

making static variables in member functions independent for each instance

Given the class:
class A {
Public:
void foo() {
static int i;
i++;
}
};
How would you change it to prevent i from changing between instances following this example:
A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 1
o3.foo(); // i = 1
o1.foo(); // i = 2
i.e. allocate memory for i on every instance.
EDIT:
Yes, you can add i as an instance variable, but what if you need these counters in various (independent) functions ? I am looking to limit the scope of the variable only to the function ("in member functions"). It would seem awkward to add variables such as i, c, counter, counter_2 to the class if you need various counters, would it not ?
class A
{
public:
int i = 0;
void foo(){
++i;
}
};
is the normal way: i is now a member variable of the class. Clearly you don't want to use static.
In circumstances where declaring data members become costly(need for sparse members that are not used so often), An instance indepent collection - normally an associative one - may come in handy. Knowing nothing more about the OP's intention, std::map family of classes can be used as first speculation. We need to have one counter per visited object in A::foo, but not for unvisited instances(i.e. A instances not calling A::foo). This was the the simplest first solution I came up with:
void A::foo(){
static std::map<A*,std::size_t> i;
++i[this];
//...
};
Upon call to std::map::operator[] on an object not in the map, the associated value is default constructed in a memory location already zeroed by the allocator( in short words 1st-timers are automatically initialized to 0).

Is there a name for non-OOP version of 'property'?

AFAIK In C++, we call the getter/setter function as 'property'.
The getter/setter is used to get/set a member variable.
One of the advantages of doing this is that we can listen for change, like this:
// In header:
class XXX {
int m_width{};
void OnWidthChanged() {
// do something...
}
public:
int Width() const {
return m_width;
}
void Width(int val)
m_width = val;
this->OnWidthChanged();
}
};
// In CPP:
XXX my_xxx;
my_xxx.Width(123);
cout << my_xxx.Width() << endl;
Now I found static variable can be used to implement similar thing, in a non-OOP fashion I know it cannot handle multiple-instance, so let's just assume XXX is an object that has only 1 instance.
// In header:
int XXX_Width(bool set = false, int val = 0);
void XXX_OnWidthChanged();
// In CPP:
int XXX_Width(bool set, int val) {
static int width = 0;
if (set) {
width = val;
XXX_OnWidthChanged();
}
return width;
}
XXX_Width(true, 123);
cout << XXX_Width() << endl;
My question is, is there a name or term for this kind of functions functions like XXX_Width()?
I'm looking for a name so I can google search for related information.
I'm not asking for name for OnWidthChanged().
Lots of confusion about terminology here.
OOP simply means that you have autonomous classes with their functionality encapsulated. Both your examples use OO, though if they are bad or good design is another matter.
Now I found static variable can be used to implement similar thing, in a non-OOP fashion:
There is nothing non-OOP with your example. It is however probably bad OO design, since multiple instances of your class may access that same function. It is also bad design from a thread-safety perspective.
Sometimes, using static variables locally is perfectly fine though, like for example when implementing "singleton" classes.
In C++, we call the getter/setter function as 'property'
No, that is not a common term. Getter/setter functions are called members, or member functions. Or possibly public member functions, since by definition those must be public. Another term used for them is methods.
The term property is most often used to describe public member variables. Often RAD tools use the term property for such variables.
My question is, is there a name or term for this kind of functions?
A function which is specified by the caller, but called by someone else (the class, the OS, an interrupt etc) is universally called callback function. This is a fairly broad term.
In your case, you seem to use callback functions like "events" - an event is a kind of callback function but a higher level concept. Code like your example could be used for so-called "event-driven design", which is also popular among RAD tools.
The 1st point that should be made is that your "property block" or "getter/setter" are non-conformant. The expected declarations look like:
int Width() const;
void Width(const int);
So when you change the setter to: XXX& Width(int) it becomes clear that you aren't talking about "property blocks" or "getter/setters". So let's talk about what your setter does look like:
It makes a call after width changes. Such a call would typically be an interupt or a signal
It returns a non-const reference to the object. This is the behavior of an operator which notably do have outside class versions
Now let's talk about your function: int XXX_Width(bool set = false, int val = 0) You've set it up with default arguments such that it could behave as either the setter or the getter in your example, notwithstanding the weirdness of your getter's return.
Given the distinction between the 2 options you present, you seem to be asking:
Is there a name for using a functions static variable instead of defining a function and providing getter/setters for a member variable?
A function scoped static variable is called a static local variable.
One word of wisdom on static local variables:
A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared [source]

getting user input into a class statically in C++

I have a large simulation written in C++. The main working unit for the simulation is a class that represents neurons. To do its calculations, each instance of the neuron class needs access to the temperature. Each simulation uses tens of thousands of instances of the neuron class and the temperature is the same value for each neuron. For this reason, I would rather not have it be stored as regular member data, so each instance of the neuron class doesn't have to take up memory storing its own copy. I would ideally store it as a static member variable (or, as a last resort, a global variable). However, I need the temperature to be determined at run-time as user input. Is there any simple way to give the neruon class access to this variable in the manner of static member data?
Just because a variable is static, doesn't mean that it also needs to be const. See the below code.
#include <cassert>
struct X {
int member;
static int static_var;
};
int X::static_var;
int main() {
X x;
x.member = 1;
x.static_var = 2;
X y;
y.member = 3;
y.static_var = 4;
X::static_var = 5;
assert(x.static_var == y.static_var);
assert(&x.static_var == &y.static_var);
}
Just provide a static member function, which you can call at runtime and set the temperature member.
Alternatively, You could just make the static member public and set it directly, As a personal choice I prefer doing it through member function though.
class Neuron
{
public:
static void setTemperature(int i)
{
mTemp = i;
}
private:
static int mTemp;
};
int Neuron::mTemp = 0;
int main()
{
//Get Temperature at run-time
Neuron::setTemperature(10);
return 0;
}
I see something like this as a good candidate for a global. What if you add something to your simulation that also uses the temperature?
Since a global variable could be modified by anyone at any time, I suppose the best solution IMO is to have a globally-scoped (standard) function like getTemperature(). Then any object could call it at any time. Putting it in its own C file and marking it static makes it only accessible through a mechanism you choose.
Also alternatively, if one doesn't like that, would be to create a static Globalsor SimulationInputs class, with getters for things just like temperature.
Singleton, global, static data, oh my!
The data model for C++ allows us to have global access to data, and to restrict the number of instances of that data, through various mechanisms and hacks.
Just because we can, though, doesn't mean we should. And just because you have a design where it could be a solution, doesn't mean you should choose it.
Normally, you have classes which manage their own data. If an object needs some data which it doesn't manage, you pass it as a parameter.
So, pass the temperature as a parameter. Explicit is better than implicit.
You mentioned that you have a class representing Neurons. I assume you meant Neuron, but it would also be good to have a Neurons class which keeps them all together. It can have a temperature which it applies to all the Neuron calculations.

Address of a static variable

I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
Each class would then be identified by unique int const *. Is this guaranteed to work? Will the returned pointer really be unique? Is there any better simpler solution?
I have also thought about pointer to std::type_info:
class A {
static std::type_info const *GetId() {
return &typeid(A);
}
};
Is that better?
Edit:
I don't need to use the id for serialization. I only want to identify a small set of base classes and I want all subclasses of some class to have the same id
Yes, this will work. Each static local will be given distinct memory location at the time when the module is loaded and it will persist until the module is unloaded. Remember, static locals are stored in static storage that is distributed during compilation and they persist till the module gets unloaded, so they will have distinct memory locations.
The address of static variable is guaranteed to be unique and the same in all translation units.
It is not a good idea because it requires you to add code to every class to be identified.
The pointers to type info objects are not guaranteed to be unique, but the type info objects themselves are guaranteed to compare as equal for a given class, and as unequal for distinct classes. This means you can use small wrapper objects that carry type info pointers, and the delegate the comparisions to the type info objects. C++11 has such a wrapper in the standard library, and if you don't have access to that, there is one in Andrei Alexandrescu's "Modern C++ Design", and therefore probably also in the Loki library, there is probably one in Boost, and there is one on my Wordpress blog – it's not like you to have invent one from scratch.
If, however, the id's are to be used for serialization, then you need id's that are valid across builds. And in that case you you need strings or UUIDs. I would go with UUIDs.
To associate a class with an UUID you can in general use a type traits class. Or if you're only doing Windows programming then you can use Visual C++'s language extensions for this. I think but I am not 100% sure that those language extensions are also implemented by g++ (in Windows).
Cheers & hth.
As I have noticed at least MSVC 2008 or 2010 optimizes the static variable, so that the following GetId function returns same address even for different classes.
static int const *GetId() {
static const int i = 0;
return &i;
}
Therefore address of uninitialized constant static variable may not be used for identification. The simplest fix is to just remove const:
static int *GetId() {
static int i;
return &i;
}
Another solution to generate IDs, that seems to work, is to use a global function as a counter:
int Counter() {
static int i = 0;
return i++;
}
And then define the following method in the classes to be identified:
static int GetId() {
static const int i = Counter();
return i;
}
As the method to be defined is always the same, it may be put to a base class:
template<typename Derived>
struct Identified {
static int GetId() {
static const int i = Counter();
return i;
}
};
And then use a curiously recurring pattern:
class A: public Identified<A> {
// ...
};
The address of the static int is guaranteed to be unique for each
function (and the same for every call to the same function). As such,
it can work very well as an id within a single execution of the code.
The address could conceivably change from one run to the next, and will
often change from one compilation to the next (if you've changed
anything in the code), so it is not a good solution for an external id.
(You don't say whether the id must be valid outside a single execution
or not.)
The address of the results of a typeid is not guaranteed to be the
same each time you call the function (although it probably will be).
You could use it to initialize a pointer, however:
static std::type_info const& GetId()
{
static std::type_info const* id = &typeid(A);
return id;
}
Compared to using int*, this has the advantage of providing additional
information (e.g. for debugging). Like int*, the identifier may be
different from one run to the next; A::GetId()->name() will point to
the same '\0' terminated string (although again the address might be
different) provided you compile with the same compiler. (As far as I
can tell, the standard doesn't guarantee this, but in practice, I think
you're safe.) Change compilers, however, and all bets are off.
The solution I've used in the past is something like:
static char const* GetId()
{
return "A"; // Or whatever the name of the class is.
}
This provides a unique identifier, easily compared, within a single
execution of the code, and a string value which can be used as an
external identifier, and which is guaranteed across all compilers. We
implemented this as a macro, which defined both the static function, and
a virtual function which returned it, e.g.:
#define DECLARE_IDENTIFIER(name) \
static char const* classId() { return STRINGIZE(name); } \
virtual char const* id() { return classId(); }
This results in a very fast (but limited) RTTI, and supports external
identifiers for serialization and persistency.
The int* method would be unique, since a different static memory cell must be allocated for each static variable, and I'd guess it is simpler to understandthan the type_info idea.
Clearly pointers to different variables must have different values. Just watch out if you choose to derive a subclass of A. You need to decide what your policy is for id. If you did nothing then the subclass would have the same id.
In general, you really really want to avoid hacky things like this. If I really had to do this, I'd look at using some UUID system (there's a library in Boost for that, but I'm not very familiar with it), or some singleton that maintained a list of these objects for whatever purpose you need.
Static variables are initialized before Heap & Stack memory so yeah it will be unique.
Quirky though.
Because you will have to add this method to all classes that require a UID you may as well do this.
unsigned int getUID()
{
return 12;
}
The advantage of this is that the compiler will be able to use a jump table if you are using this for RTTI for switching on type, which will not be possible with two pointers because the jump table would be very sparse.
The (minor) disadvantage is you need to keep track of which identifiers have been taken.
A major disadvantage of the first method you presented is that the same numbers cannot be used to identify objects because the virtual getUID() method won't be able to take the address of the variable in another function's scope.

What is the rationale for not having static constructor in C++?

What is the rationale for not having static constructor in C++?
If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:
//illegal C++
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
//illegal constructor!
static sample()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
};
In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.
So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!
Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.
Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:
//called before main()
int static_main() {
ClassFoo();
ClassBar();
}
with appropriate declarations:
class ClassFoo {
static int y;
ClassFoo() {
y = 1;
}
}
class ClassBar {
static int x;
ClassBar() {
x = ClassFoo::y+1;
}
}
So the answer is, there is no reason it isn't there, at least not a technical one.
This doesn't really make sense for c++ - classes are not first class objects (like in e.g. java).
A (static|anything) constructor implies something is constructed - and c++ classes aren't constructed, they just are.
You can easily achieve the same effect though:
//.h
struct Foo {
static std::vector<std::string> strings;
};
//.cpp
std::vector<std::string> Foo::strings(createStrings());
IMO there's just no need for one more syntactic way of doing this.
In which translation unit would the static objects be placed?
Once you account for the fact that statics have to be placed in one (and only one) TU, it's then not "very difficult" to go the rest of the way, and assign values to them in a function:
// .h
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
};
//.cpp
// we'd need this anyway
int sample::some_integer;
std::vector<std::string> sample::strings;
// add this for complex setup
struct sample_init {
sample_init() {
sample::some_integer = 100;
sample::strings.push_back("stack");
sample::strings.push_back("overflow");
}
} x;
If you really want the code for sample_init to appear in the definition of class sample, then you could even put it there as a nested class. You just have to define the instance of it in the same place you define the statics (and after they've been initialized via their default constructors, otherwise of course you can't push_back anything).
C# was invented 15-20 years after C++ and has a completely different build model. It's not all that surprising that it offers different features, and that some things are less simple in C++ than in C#.
C++0x adds a features to make it easier to initialize vectors with some data, called "initializer lists"
You could get by with putting your "static" members in their own class with their own constructor that performs their initialization:
class StaticData
{
int some_integer;
std::vector<std::string> strings;
public:
StaticData()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
}
class sample
{
static StaticData data;
public:
sample()
{
}
};
Your static data member is guaranteed to be initialized before you first try to access it. (Probably before main but not necessarily)
Static implies a function that is disassociated with an object. Since only objects are constructed, it is not apparent why a static constructor would have any benefit.
You can always hold an object in a static scope which has been constructed in a static block, but the constructor you would use would still be declared as non-static. There's no rule that indicates you can't call a non-static method from a static scope.
Finally, C++ / C defines the start of a program to be when the main function is entered. Static blocks are called prior to the entry of the main function as part of setting up the "environment" of the evaluated code. If your environment dictates full control over the set-up and tear-down, then it's easy to argue that it's not really some environmental fixture as much as an inherit procedural component of the program. I know that the last bit is sort of code-philosophy (and that it's rationale could be interpreted differently), but one shouldn't put critical code "before" the official start of an executable's handing off "full control" to the code written by the programmer.