March 26, 2005

I'm not dead

It's been 3 weeks since my last post. I'm not dead. I've been busy working on various projects. None of them are in a state that I can post anything concrete. Last week I learned two scripting languages: Ruby and Lua. The first thing I noticed was how much more productive I was using a scripting language than C# or C++. I think it was mostly the dynamic typing and certain language features like closures and coroutines. Closures are awesome. They do all the things I wish C# delegates would do.

After writing my first program in Ruby, another thing I noticed was how short it was considering the amount of stuff it did. I also noticed that the code was considerably narrower than a C# or C++ program would be, probably because of all the type conversions I would have used in a statically typed language. Overall I think the Ruby program had about one quarter the surface area :)

Apart from that I've been thinking about next generation of consoles, parallel processing in particular. Nothing to report yet.

Today I messed around trying to write a C++ garbage collector. I discovered a diabolical way to abuse the assignment operator. Unless you tell it not to, a C++ compiler will automatically generate an assignment operator (and various constructors) for each class. This default assignment operator will assign member variables component-wise. So if you use smart pointers to represent references between objects, and override the smart pointer's assignment operator, it is possible to use the assignment operator of the containing class to find all the reference members.
template < typename T >
class SmartPointer
{
public:

SmartPointer &operator=(const SmartPointer &p)
{
if (garbageCollecting)
{
handlePointer(*this);
}
object = p.object;
return *this;
}

// ...
};

class MyClass
{
SmartPointer< OtherClass > p;
};

MyClass myObject;

garbageCollecting = true;

// Assigning myObject to itself causes handlePointer to
// be called for myObject.p
myObject = myObject;

Of course, this will only work if you write classes in a certain way. In particular, all the members have to handle being assigned to themselves. I can see STL containers going a bit funny. Still, it's keeping me entertained.

Comments:
Hi Al,
I heard once that there are two things that every class needs: a copy constructor and an assignment operator. Makes sense since, as you pointed out, they get provided for you by C++. Guess I better go add those to my math library.

[joey]
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?