Saturday, 30 July 2011

Variable initializers and global variables

See, I've been musing over global variables. The problem is that in "DeadMG++", it's very difficult to go around *not* using global variables, being as how stuff like types and functions used to be constants and now they're not. One of the most fundamental problems that I've got when dealing with them is initializing them. For example, my post on Const's definition the other day actually violates normal "DeadMG++" rules- that code goes in a function. Now, we can define a lambda that executes itself inline to define arbitrarily complex initializations. For example,

using Standard;
using Containers;
using Attributes;
Map(String, String).Attribute(Const) x = [&] {
    Map(String, String) retval;
    retval["ohai"] = "nub";
    return retval;
}();


This is a trick I've used in C++- it's better than initializer lists, in my opinion. The problem is that initializing some complex types depends on referring to them- similar to using this in the initializer list. For example, my previous definition of Const depends on recursively applying Const to it's member types. This is illegal in C++, but I've decided that it will have to be legalized in "DeadMG++". Referring to a variable in it's initializer will be legal, and it will be legal to take a pointer to it, however actually accessing any part of it will be Bad™, unless explicitly initialized first.

using Standard;
using Containers;
using Attributes;
Map(String, String).Attribute(Const) x = [&] {
    x = Map(String, String)(); 
    x["ohai"] = "nub";
}();

Alternatively, a sort of lazy-evaluation could become a common idiom. Perhaps most types, most Standard types, will simply take a function object that will initialize them as a constructor argument after default-initializing as a construction option.

using Standard;
using Containers;
using Attributes;
Map(String, String).Attribute(Const) x([&] {
    x["ohai"] = "nub";
});

Of course, this is pretty handy in C++ too. In fact, some of the lazy expression evaluation can be performed in C++, if you have a lib that supports it in combination with the new lambda functions. I think I'd rather have this than init lists.

No comments:

Post a Comment