侯老师--STL源码剖析--书中的疑问二 (转)

侯老师--STL源码剖析--书中的疑问二 (转)[@more@]

 

XML:namespace prefix = o ns = "urn:schemas- microsoft-com: Office:office" />

侯老师--STL源码剖析--书中的错误二

前言

我在看侯捷的STL源码剖析一书中”第二章设计一个阳春的空间配置器JJ::allocator(第45页)看到了如下的伪代码,我认为是有错误的,代码如下:

命名空间JJ中代码

……

template

inline void _construct(T1* p, const T2& value)

{

  new(p) T1(value);

}

……

template

class allocator

{

  ……

typedef T* pointer;

……

void construct(pointer p, const T& value)

{

  _construct(p,value);

}

……

}

  现在让我们假设使用allocator空间配置器,当系统调用construct(…)时其内部委托_construct(…)执行,这时模板函数_construct的T1为pointer(即int*),当执行new(p) T1(value);语句时,其变成了new int*(value)。这样能编译通过吗?就算能,但它的结果不是我们所想得到的。大家认为呢?为此我看了STL的实现源码,发现的确和侯老师写的不同。源码如下:

SGI的STL源码

template

struct __allocator {

  _Alloc __underlying_alloc;

 

  typedef size_t  size_type;

  typedef ptrdiff_t difference_type;

  typedef _Tp*  pointer;

  typedef const _Tp* const_pointer;

  typedef _Tp&  reference;

  typedef const _Tp& const_reference;

  typedef _Tp  value_type;

 

  template struct rebind {

  typedef __allocator<_tp1 _alloc> other;

  };

 

  __allocator() __STL_NOTHROW {}

  __allocator(const __allocator& __a) __STL_NOTHROW

  : __underlying_alloc(__a.__underlying_alloc) {}

  template

  __allocator(const __allocator<_tp1 _alloc>& __a) __STL_NOTHROW

  : __underlying_alloc(__a.__underlying_alloc) {}

  ~__allocator() __STL_NOTHROW {}

 

  pointer address(reference __x) const { return &__x; }

  const_pointer address(const_reference __x) const { return &__x; }

 

  // __n is peRmitted to be 0.

  _Tp* allocate(size_type __n, const void* = 0) {

  return __n != 0

  ? static_cast<_tp>(__underlying_alloc.allocate(__n * sizeof(_Tp)))

  : 0;

  }

 

  // __p is not permitted to be a null pointer.

  void deallocate(pointer __p, size_type __n)

  { __underlying_alloc.deallocate(__p, __n * sizeof(_Tp)); }

 

  size_type max_size() const __STL_NOTHROW

  { return size_t(-1) / sizeof(_Tp); }

 

  void construct(pointer __p, const _Tp& __val) { new(__p) _Tp(__val); }

  void destroy(pointer __p) { __p->~_Tp(); }

};

  注意加黑部分,源码中用的是__Tp(就是value_type),所以侯老师的_construct函数应改为如下定义:

  template

  inline void _construct(T1 p, const T2& value)

  {

  new(p) T2(value);

  }

首先声明一下,我是非常非常崇拜侯老师的,侯老师的书写的真的十分的棒,所以才看的仔细,但是这不代表我说的一定对,侯老师一定写错了。我只是把我个人的观点写出来,请大家批评指教,共同进步吗!如果能够得到侯老师的指点是再好不过了^_^。

总之,请大家多多批评指教,来信至Mailto:来信至ccplusplus@21cn.com" rel="nofollow">ccplusplus@21cn.com。

 

  致谢!

            袁凯

           2001-11-13


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10752043/viewspace-990186/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10752043/viewspace-990186/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值