下面是static_constructable类模板的实现:
template
class static_constructable
{
private:
struct helper{
helper(){
T::static_constructor();
}
};
protected:
static_constructable(){
static helper placeholder;
}
};
class static_constructable
{
private:
struct helper{
helper(){
T::static_constructor();
}
};
protected:
static_constructable(){
static helper placeholder;
}
};
上面的实现把对A::static_constructor()的回调放到内部类helper的构造函数中;并在static_constructable()中定义一个helper局部静态变量;C++保证在构造派生类 A的对象时,会先调用基类static_constructable的构造函数,且静态局部变量只会构造一次,这样就达到调用一次且仅一次A::static_constructor()的目的。< /span>
static_constructor类模板简单地模拟了C#的静态构造函数机制,它具有以下特点:
1. 在第一次构造类对象之前自动调用类提供的静态构造函数
2. 静态构造函数被调用的时机是确定的
3. 利用了C++的局部静态变量初始化机制保证了线程安全性(更正:实际并非线程安全,C++标准不涉及多线程问题,而一般编译器实现也非线程安全,更多参见评论部分)
4. 基于继承的实现机制并未改变派生类的对象内存布局
不过,和本文开始列出的C#静态构造函数的几个特点相比,本实现还有明显的不足:无法通过调用类A的静态方法触发静态构造函数;类A的静态构造函数必须是public的。希望有更好解决方案的朋友不吝赐教,也欢迎对此话题感兴趣的朋友交流探讨!