《stl源码剖析》第二级配置器代码编译不过
enum {__ALIGN = 8}; //上调边界
enum {__MAX_BYTES =128}; //小型区块的上限
enum {__NFREELISTS = __MAX_BYTES/__ALIGN}; //free_lists 个数
//第二级配置器
template<bool threads, int inst>
class __default_alloc_template
{
private:
//节点结构
union obj
{
union obj * free_list_link;
char client_data[1];
};
private:
static obj* volatile free_list[__NFREELISTS];
};
//在这里编译不过,vc2010
template<bool threads,int inst>
__default_alloc_template<threads,inst>::obj* volatile
__default_alloc_template<threads.inst>::free_list[__NFREELISTS]=
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
1,这里free_list[__NFREELISTS]是个obj*数组,volatile 修饰obj类型,让编译器不要去优化
错误提示如下
error C1903: unable to recover from previous error(s); stopping compilation
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
2,我认为下面的给静态变量赋值的代码应该是
template<bool threads,int inst>
__default_alloc_template<threads,inst>::obj* volatile
free_list[__NFREELISTS]=
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
上面的语法该如何解释呢
[解决办法]
__default_alloc_template<threads.inst>::free_list中的threads.inst应为threads,inst。
还有,__default_alloc_template<threads,inst>::obj*前应有typename修饰。
对于第二个问题,free_list是__default_alloc_template的静态成员,在类外定义时应加上__default_alloc_template<threads,inst>限定词,这是基本语法。
聚集元素与聚集本身是两件不同的物件,因此obj*前的限定词仅能用来修饰obj*,是不能同时用来修饰free_list的,这个道理跟函数形参与返回值之间的不同类似。