posts - 13, comments - 4, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Imperfect C++ 读书笔记(六)

Posted on 2008-11-26 20:44 Batiliu 阅读(438) 评论(0)  编辑 收藏 引用 所属分类: 读书笔记

返回值生命期

在本章,我们通过考察5个不完美的将整形转换为字符串类型的技术,探讨下C++中返回值生命期的各种问题和陷阱,最后总结垃圾收集机制的一个实际价值。

  1. integer_to_string<>
    template<typename C>
    C const* integer_to_string(C* buf, size_t cchBuf, sint8_t i)
    {
        return signed_integer_to_string(buf, cchBuf, i);
    }
    ...
    template<typename C>
    C const* integer_to_string(C* buf, size_t cchBuf, uint8_t i)
    {
        return unsigned_integer_to_string(buf, cchBuf, i);
    }
     
    template<typename C, typename I>
    inline const C *signed_integer_to_string(C* buf, size_t cchBuf, I i)
    {
        C* psz = const_cast<C*>(unsigned_integer_to_string(buf, cchBuf, i));
        if (i < 0)
        {
            --psz;
            *psz = C('-');
        }
        return psz;
    }
     
    template<typename C, typename I>
    inline const C* unsigned_integer_to_string(C* buf, size_t cchBuf, I i)
    {
        C* psz = buf + cchBuf - 1;
        *psz = 0;
        do
        {
            unsigned lsd = i % 10;
            i /= 10;
            --psz;
            *psz = get_digit_character<C>()[lsd];
        } while (i != 0);
        return psz;
    }
    template<typename C>
    const C* get_digit_character()
    {
        static const C s_characters[19] =
        {
            '9', '8', '7', '6', '5', '4', '3', '2', '1',
            '0',
            '1', '2', '3', '4', '5', '6', '7', '8', '9'
        };
        static const C* s_mid = s_characters + 9;
        return s_mid;
    }

    该方案效率很高,仅相当于spintf()开销的10%。然而,也并非完美无缺。首先,它不算十分简洁:需要用户提供缓冲区的指针和缓冲区的长度。其次,更重要的一点,用户提供的缓冲区长度有可能是错误的。如果太小,也许还能在调试版中引发一个断言,如果大于缓冲区真实的长度,就有可能发生缓冲区溢出。

  2. TSS

    利用TSS(Thread-Specific Storage,线程相关存储),我们可以提供一个线程安全的内部缓冲区,就只需提供待转换的整型值一个参数即可了。

    template<typename C, typename I>
    C const* int_to_string(I i)
    {
        const size_t CCH = 21;    // 足以容纳64位有符号整型的最大值
        C *  buf = get_tss_buffer<C, CCH>();
        return integer_to_string(buf, CCH, i);
    }
     
    template<typename C, size_t CCH>
    C* get_tss_buffer()
    {
        __declspec(thread) static C s_buffer[CCH];
        return s_buffer;
    }

    注:__declspec(thread)是微软Win32编译器提供的扩展,如果需要跨平台或跨编译器,可以考虑选择其他合适的TLS库。
    该方案有个小小的不便就是,无法推导字符类型了,需要显式地参数化函数模板。如:int_to_string<char>(10)。
    然而,还有个更显著的缺陷,就是无法再单个表达式中被多次调用。如:printf("%s, %s", int_to_string<char>(5), int_to_string<char>(10));

  3. 扩展RVL

    为了解决方案2的在同一表达式中不能连续调用的问题,可以运用一个技巧让其冲突的可能性降低。

    template<typename C, size_t CCH>
    C* get_tss_buffer()
    {
        const size_t DEGREE = 32;
        __declspec(thread) static C s_buffer[DEGREE][CCH];
        __declspec(thread) static size_t s_index;
        s_index = (s_index + 1) % DEGREE;
        return s_buffer[s_index];
    }

    这里的32只是一个猜测值,即假定单个表达式中最多不超过32个同一类整型到字符串的转换。32表示“安全”和栈大小之间的一个折衷,相对于方案2给用户提供了一种虚假的安全感,所以并不推荐使用。

  4. 静态数组大小决议

    针对方案1,我们利用编译器能够推导出数组的静态大小。我们可以定义integer_to_string()函数的一个新的重载版本,它接受一个数组为参数,而不是自带缓冲区长度的指针。

    template<typename C, size_t N>
    C const* integer_to_string(C(&buf)[N], sint8_t i)
    {
        STATIC_ASSERT(!(N < printf_traits<sint8_t>::size));
        return integer_to_string(buf, cchBuf, i);
    }

    该方案消除了错误的缓冲区长度被传递给函数的可能性,更妙的是,我们可以使用静态断言来进行编译器检查,从而确保缓冲区长度是足够的。该方案是线程安全的,且不需要进行任何显式实例化,如:

    uint64_t i = ...
    char buff[12];
    char const* s = integer_to_string(buff, i);

    这个方案唯一的缺点就是我们仍然还得提供一个缓冲区。

  5. 转换垫片
    最后一个解决方案,不再像前面的解决方案一样返回一个指针,它走了另一条不同的路:使用一个代理类,返回该代理类的实例。当然,幕后仍然是integer_to_string()函数在承担着实际的转换工作。
    template<typename C, typename I>
    class int_to_string_proxy
    {
    public:
        typedef C char_type;
        typedef I int_type;
    public:
        int_to_string_proxy(int_type i)
            : m_result(integer_to_string(m_sz, dimensionof(m_sz), i))
        {}
        int_to_string_proxy(int_to_string_proxy const& rhs)
            : m_result(m_sz)
        {
            char_type* dest = m_sz;
            char_type const* src = rhs.m_result;
            while (0 != (*dest++ = *src++))
            {}
        }
        operator char_type const* () const
        {
            return m_result;
        }
    private:
        char_type const * const m_result;
        char_type m_sz[21];
    private:
        int_to_string_proxy& operator =(int_to_string_proxy& rhs);
    };
     
    template<typename C, typename I>
    int_to_string_proxy<C, I> int_to_string(I i)
    {
        return int_to_string_proxy<C, I>(i);
    }

与所有转换垫片一样,该方案受到RVL-PDP(析构后指针)问题的困扰。它需要在表达式中立即使用返回值,而不应该保留到以后使用。

在这里,我们发现了一个垃圾收集机制真正能够发挥无可比拟的地方。借助于垃圾收集,前面讨论的RVL(返回值生命期)问题迎刃而解。由于垃圾收集的工作机制是释放那些不再被活跃代码所引用的内存,所以毫无疑问,当一个指向堆分配的内存块的指针在仍然被需要的时候是被会失效的。我们所要做的就是返回一个新分配的堆内存块而已。

 

多维数组

C/C++不支持各维大小都是动态的多维数组,但我们可以借助语言内建对多维数组进行“切片”的能力实现一个自定义的多维数组类(容器)。

作者给出的fixed_array系列多维数组类模板具有以下几个显著的特征:

  1. 每一个模板都维护一个指向一维内存快的指针,其他存放的是逻辑上N维的数组元素。
  2. 每一个类都有一个dimension_element_type成员类型,该成员的类型对一维数组类其实就是value_type,对高维数组类就是比它低一维的数组模板。
  3. begin()和end()方法返回的迭代器表示整个多维数组所有的元素集合区间,这便意味着,可以是使用同一stl算法(如 std::for_each())来处理不同维数的数组。
  4. 一个数组模板不但自身能够作为一个完整的多维数组类,而且还能够作为比它更高维的数组模板的子数组切片。作为完整多维数组类时,其模板参数R为true,其标准构造函数会分配相应的内存。作为其他更高维度数组的子数组切片时,其模板参数R为false,其切片构造函数只是接受一个相应的子数组切片指针。
template<typename T, 
    typename A = typename allocator_selector<T>::allocator_type, 
    typename P = do_construction<T>, 
    bool R = true>
class fixed_array_2d : protected A, public stl_collection_tag
{
public:
    typedef fixed_array_2d< T, A, P, R >  class_type;
    typedef fixed_array_1d< T, A, P, false >  dimension_element_type;
    typedef A  allocator_type;
    typedef T  value_type;
    typedef value_type &  reference;
    typedef value_type const &  const_reference;
    typedef value_type *  pointer;
    typedef value_type const *  const_pointer;
    typedef size_t  size_type;
    typedef size_t  index_type;
    typedef ss_ptrdiff_t  difference_type;
    typedef bool  bool_type;
    typedef pointer_iterator< value_type, pointer, reference >::type  iterator;
    typedef pointer_iterator< value_type const , const_pointer,    const_reference >::type  const_iterator;
 
// 构造函数
private:
    // 切片构造
    fixed_array_2d(T *data, index_type d0, index_type d1);
public:
    // 标准构造
    fixed_array_2d (index_type d0, index_type d1);
    fixed_array_2d (index_type d0, index_type d1, allocator_type const &ator); 
    fixed_array_2d (index_type d0, index_type d1, value_type const &t); 
    fixed_array_2d (index_type d0, index_type d1, value_type const &t, allocator_type const &ator); 
    fixed_array_2d (class_type const &rhs);
    ~fixed_array_2d();
 
    allocator_type  get_allocator () const;
    void  swap (class_type &rhs); throw ();
 
// 访问
public:
    reference  at (index_type i0, index_type i1);
    const_reference  at (index_type i0, index_type i1) const;
    reference  at_unchecked (index_type i0, index_type i1);
    const_reference  at_unchecked (index_type i0, index_type i1) const;
    reference  operator(); (index_type i0, index_type i1);
    const_reference  operator(); (index_type i0, index_type i1) const;
    dimension_element_type  at (index_type i0); 
    const dimension_element_type  at (index_type i0) const;  
    dimension_element_type  at_unchecked (index_type i0); 
    const dimension_element_type  at_unchecked (index_type i0) const;  
    dimension_element_type  operator[] (index_type i0); 
    const dimension_element_type  operator[] (index_type i0) const;  
 
    reference  front ();
    reference  back ();
    const_reference  front () const;
    const_reference  back () const;
 
    pointer  data ();
    const_pointer  data () const;
 
// 迭代
public:
    iterator  begin ();
    iterator  end ();
    const_iterator  begin () const;
    const_iterator  end () const;
 
// 状态
public:
    index_type  dimension0 () const;
    index_type  dimension1 () const;
    index_type  size () const;
    bool_type  empty () const;
 
    static size_type  max_size ();
 
// 实现
private:
    pointer         allocate_(size_type n);
    void            deallocate_(pointer p, size_type n);
 
    pointer         data_();
    index_type      calc_index_(index_type i0, index_type i1) const;
    void            range_check_(index_type i0, index_type i1) const;
    void            range_check_(index_type i0) const;
 
    allocator_type& get_allocator_();
 
// 成员
private:
    T*          m_data;
    index_type  m_d0;
    index_type  m_d1;
    size_type   m_size;
 
    friend class fixed_array_3d<T, A, P, true>;
    friend class fixed_array_3d<T, A, P, false>;
 
// 声明但不实现
private:
    class_type const& operator =(class_type const& rhs);
};

另外,C/C++对固定大小的数组支持是无容置疑的,但为了获得通过bein()/end()来获得对整个数组进行迭代的能力,我们也设计了一组模板类来模拟静态多维数组。static_array自身并不进行任何形式的内存分配:如果它的身份是作为一个切片代理,它只会保存一个指向数组切片的指针;倘若它本身作为一个完整的数组,则会包含一个完整的N维内建数组。

template<typename T,
    size_t N0,
    size_t N1,
    typename P = do_construction<T>,
    typename M = T[N0 * N1]>
class static_array_2d : public null_allocator<T>, public stl_collection_tag
{
    ...
private:
    M   m_data;
};
 
 

仿函数

泛化的仿函数 —— 类型隧道(Type Tunneling):是一种通过访问垫片使两个逻辑相关但物理不相关的类型能够互操作的机制,垫片允许一个外部类型通过一个接口以一种可识别且兼容的形式呈现于内部类型的面前。

template<typename C, 
    typename A = C const *>
class is_large : public std::unary_function<A, bool>
{
public:
    template<typename S>
    bool operator ()(S const& file) const
    {
        return is_large_(c_str_ptr(file));    // c_str_ptr垫片
    }
private:
    static bool is_large_(C const* file)
    {
        ...
    }
};
 
glob_sequence gs("/usr/include/", "impcpp*");
std::count_if(gs.begin(), gs.end(), is_large<char>());
 
glob_sequenc_w gsw(L"/usr/include/", L"impcpp*");
std::count_if(gsw.begin(), gsw.end(), is_large<wchar_t>());
 
readir_sequence rs("/usr/include/");
std::count_if(rs.begin(), rs.end(), is_large<char>());

局部类

虽然某些老版本的编译器不支持局部仿函数类用于STL算法(VS2008支持的还不错),但当我们遇到回调枚举API时,局部类是个非常不错的选择。

HWND FindChildById(HWND hwndParent, int id)
{
    if (::GetDlgCtrlID(hwndParent) == id)
    {
        return hwndParent;
    }
    else
    {
        struct ChildFind
        {
            ChildFind(HWND hwndParent, int id)
                : m_hwndChild(NULL)
                , m_id(id)
            {
                ::EnumChildWindows(hwndParent, FindProc, reinterpret_cast<LPARAM>(this));
            }
 
            static BOOL CALLBACK FindProc(HWND hwnd, LPARAM lParam)
            {
                ChildFind& find = *reinterpret_cast<ChildFind*>(lParam);
                return (::GetDlgCtrlID(hwnd) == find.m_id) ? 
                    (find.m_hwndChild = hwnd, FALSE) : TRUE;
            }
 
            HWND m_hwndChild;
            int const m_id;
        }find(hwndParent, id);
 
        return find.m_hwndChild;
    }
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理