Sunday, March 26, 2006

C++ Static blocks

Ok, this isn't rocket science. But every now and then I should post something technical, if only to remind myself of my primary profession.

This time it is about static blocks in C++. Now what are static blocks? They are a cool feature in Java that lets you write code that executes when a class is loaded. For example:

class InitializedVariable
{
private static Vector data;
public static void main (String args[] )
{
for ( int i = 0; i < data.size(); i++ )
{
System.out.println(data.elementAt(i) );
}
}

static {
data.insert (new Integer(10));
}
}

So, how would you do this in C++? Ofcourse, you have static variables that can be initialized before the program starts (or the library loads). But how will you insert values into a map, or a vector?

Well, the answer is simple. Use another static object. In its constructor, perform the initialization that you want. :)

#include
#include
using namespace std;
class Static
{
private:
static vector values;
public:
Static ( )
{
vector::iterator b = values.begin();
for ( ; b != values.end(); b++ )
{
cout << *b << endl;
}
}

class VectorInitializer
{
public:
VectorInitializer ( )
{
Static::values.push_back (20);
Static::values.push_back (40);
Static::values.push_back (60);
}
};

friend class Static::VectorInitializer;
};

vector Static::values;
static Static::VectorInitializer initalizer; //initializes the vector.

int main ( void )
{
Static x;
}

While on this, can someone tell me how I can get code into HTML without the associated struggle? Thanks! :)

10 comments:

Balbir said...

If you like what you see at http://balbir.blogspot.com/2006/03/gopals-static-block-example.html, I will tell you how to convert it to html. Take a guess?

BTW, static blocks first came from C# - No?

I have another interesing problem for you - how do you control the order in which these static blocks are called?

Anonymous said...

Type in word. Save as html :)

BTW this reminded me of the static order problem that Mithun solved endlessly and gave me enough fodder for bullshitting.

The simplest solution I think would be to code it up in terms of aspects. Since aspects can be ordrered declaratively(in aspectj at least), the problem is solved rather neatly. Yeah there is no solution here, but it works. I don't know if AspectC++ provides the samething.

-Uknowwho :)

Gops said...

Ballu,

I hope you don't want me to use LaTex for this as well! ;) Just kiddin'!

For the order, within a file, it just depends on the order of declaration, right? Is there any other order you are referring to?

Yo UKnowWho, a.k.a "the one who doesn't talk to mere mortals" - why do you need Aspects, when P.O.C++ is sufficient?

Anonymous said...

Take a look at this.

The file ManagedObject.h
class ManagedObject {

public :
ManagedObject() { //do whatever u want to }

// To allow others(one who manages this object) to modify managed object externally
void modifyMO(int val);
private :
vector _values;
};

The file Manager.h
#include "ManagedObject.h"
class Manager {

public:
Manager() {
_ptrMO->modifyMO(10);
_ptrMO->modifyMO(20);
}

// MOController class controls the creation and deletion of Managed Object
// and ensures that the ManagedObject is created before its first use and
// deleted only after its last use.
class MOController;

friend MOController;
private:
static ManagedObject * _ptrMO;
};

class MOController {

public :
MOController() {
if(count++ == 0)
_ptrMO = new ManagedObject();

}

~MOController() {

if(--count == 0)
delete _ptrMO;
}
private:
static int count;
};

// a static object is created in every file that includes Manager.h file
static Manager::MOController controllerObj;


The file Manager.cpp

#include "Manager.h"
int Manager::MOController::count = 0;
ManagedObject * Manager::_ptrMO = NULL;

Balbir said...

what if you have many files? How do you guarantee the order. Even in the same file C++ does *not guarantee* that they will be initialized in the order of declaration (or does it?)

Anonymous said...

Well, U-know-who is being totured into accepting java as reality :). Well Static order within translation units is defined and across translation units is not..Yeah! We all know that but shouldn't we stop bothering about such stuff and be able to declaratively say what executes after what instead of mucking through code? Across files initialization is a problem. So create a single initialize function to which all the correct iniailization functionns are added in the order you want. Make that initialize call statically and keep nothing else static. Now initialize needs to include all sorts of stuff which is baaad. So keep initialize empty and add each initialization function as "advice" at the end of the initialize function and since the order of application of aspects can be controlled, you have a declarative way of changing the order of initialization. You can do the same thing in code but it is a whole load of manual work. Yeah I also know that blog solutions will die a sorry death when the coconut-choclate sauce eater starts looking into it..but my point is that building the graph to control order of initialization is something that is now supported. We used the template mechanism with numbering first and then realized that it is reference counting(when I saw we, I mean he:) ) and so on..but I think we did not look in to the problem from a completely fresh perspective. So the vagueo in the air solution..

In general, I find aspects easier to do such things. Me no expert but the possiblities are making me see java with some respect now. As usual I talk about things I don't know..So ignore me :)

I wonder who wrote the managed code entry??

Just as an aside, me dying in coursework and will also violate blogetiquette by putting unrelated stuff here..Me working on model checking..Trying to create a specification language for model checking..Just started off..so don't ask about progress..and am interning in yahoo in summer..Long confused entry..but I am always in confusion anyway :D

Anonymous said...

The discussion began about how to get some code to execution during load time.
In the ManagedObject example above, the idea was to see how an object of one class(here it is Manager) modifies(here filling the values) the object of another class(data member of ManagedObject actually) during loadtime. If tomorrow there is a need that the Manager class has to modify an object of some other new class(say class C) again at load time, then this could easily be done by including another data member in class ManagedObject.(I should have named 'ManagedObjects' instead).But we can't miss out talking about static initialization rt ? Thats why the class MOController.

{quote}
Well, U-know-who is being totured into accepting java as reality :).
{/quote}

If a WRAPPED-GIFT is given to you, would you be happy with the fact that you have got a gift? Wouldn't you bother to remove the wrapper and see what the gift is ?
Do you share the first letter of your first name with the first letter of the first word in the following sentence "violate blogetiquette..... "? :-)

Gops said...

Whew!

These anonymous comments are becoming one mystery, eh!?

Hey, immortal one - you creating YALFMC? (Yet Another Language For Model Checking)? What aspects are you specifically targeting?

BTW, immortal (geez, I keep missing out the 't' when I type :D), the person who wrote the managed object shares the first letter of her name with Anonymous, and Asking!

Good luck with the internship. Keep us updated on how life is treating you :)

Anonymous said...

To my alter ego,
Hmm, Another anonymous entity is confusing my already confused self :)..Yes, "I violate and therefore I have a name" ;) I don't like unopened gift boxes too but once I know what is in the box, I don't want to peek again. The solution if we see is there already..there is a set of partial orders with no total ordering..So create a total order by explicitly managing it. The problem really is how to package it so that it is usable..by not so smart users like me feel happy with the gift box(or the wrapper).

and to Gops,
Well if I am 3 weeks into the project, I can't be saying much. The goal of the research is not to create yamcl.. but to investigate which methods solve which problems best(between model checking, static analysis and testing) and use one specification language to abstract that away. Since I am not saying the specific aspects, it is obvious that I am talking ahead of doing as usual ;)..I'll keep u updated when (and if) I arrive at something concrete. Otherwise life is hard..I am wrestling with building gcc and "abc" for my course projects, when I am not screwing up exams. You should definitely check out abc if you are interested. It is an extensible compiler (unlike most research compilers, both the frontend and the backends are written to enable easy extension. damn neat huh!) for compiling aspects and not surprisingly, among other things, someone has written a model checking language processor using abc. I am working on refactoring the compiler and some of its extensions. In other words I am doing nothing, just writing about a lot of things.

and about the one sharing her first name with Anonymous, Nice!!..You can always go around bragging that you interviewed her. I really thought, from the style of coding, that it was one of the ppr clones!!

-vknowwho

Gops said...

Vknowwho,

Not to sound preachy or something, but that is precisely what I felt 2 months into my thesis. I kept reading and reading and reading, without knowing what I was going to do! But things did work out - and the more you fiddle around now, the better you'll be prepared for the main event!

About the "Asking" lady, yes, I keep bragging that I 'selected' her! And that anyone who wants to judge my interviewing skills must talk to her first! :) But she thinks I am a lousy interviewer!!! So, what can I say!? ;)