A Better C++
I just wrote a neat little pair of C++ template classes that help work around some limitations in how primitive data members are initialized. Or rather, they aren't, so you have to manually initialize them in your constructor yourself. (Java lets you initialize them in the class definition, so it doesn't suffer from this problem.) Anyway, forgetting to initialize is a common source of error for me, so I came up with the following:
class MyClass { public: // note: no constructor needed! int getData() const { return m_data; } void setData(int data) { m_data = data; } private: autoinit<int, 10> m_data; // m_data is an int that is initialized to 10 automatically };
Simplified example, of course. My current implementation follows:
template<typename T, T initVal = 0> class autoinit { public: autoinit() : _value(initVal) { } autoinit(const T& t) : _value(t) { } operator T&() { return _value; } operator const T&() const { return _value; } private: T _value; };
There's a problem with the class above: it doesn't work for floats. Since you can't have an initVal for floating point types, here's one that just initializes to zero:
template<typename T> class zeroinit { public: zeroinit() : _value(0) { } zeroinit(const T& t) : _value(t) { } operator T&() { return _value; } operator const T&() const { return _value; } private: T _value; };
A note about performance: VS.NET 7.1 optimizes this guy totally away (even into a register, from my little test). gcc doesn't do as well.
I'm thinking of putting this in Empyrean... it's somewhat magical, but would make my life easier, as well as get rid of some constructors. And removing code is almost always good. (Most of the destructors are already gone, thanks to scoped pointers and other smart objects.) Either way, some of you might find this technique useful.