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

    技术2022-05-11  113

     

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

    前言

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

    命名空间JJ中代码

    ……

    template<class T1,class T2>

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

    {

        new(p) T1(value);

    }

    ……

    template <class T>

    class allocator

    {

        ……

    typedef T* pointer;

    ……

    void construct(pointer p, const T& value)

    {

        _construct(p,value);

    }

    ……

    }

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

    SGI的STL源码

    template <class _Tp, class _Alloc>

    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 <class _Tp1> struct rebind {

        typedef __allocator<_Tp1, _Alloc> other;

      };

     

      __allocator() __STL_NOTHROW {}

      __allocator(const __allocator& __a) __STL_NOTHROW

        : __underlying_alloc(__a.__underlying_alloc) {}

      template <class _Tp1>

      __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<class T1,class T2>

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

        {

            new(p) T2(value);

        }

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

    总之,请大家多多批评指教,来信至ccplusplus@21cn.com

     

        致谢!

                                                                    袁凯

                                                                 2001-11-13


    最新回复(0)