【问题标题】:inline function with empty parameter带空参数的内联函数
【发布时间】:2022-01-18 18:47:30
【问题描述】:

我正在学习 Boost 库。谁能帮我理解下面的代码。

/*!
    \fn ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest)
    \brief Equivalent of <code>std::uninitialized_copy</code> but with explicit specification of value type.
*/
template<class InputIterator, class ForwardIterator, class Alloc>
inline ForwardIterator uninitialized_copy(InputIterator first, InputIterator last, ForwardIterator dest, Alloc& a) 
{
    ForwardIterator next = dest;
    BOOST_TRY {
        for (; first != last; ++first, ++dest)
            boost::allocator_construct(a, boost::to_address(dest), *first);
    } BOOST_CATCH(...) {
        for (; next != dest; ++next)
            boost::allocator_destroy(a, boost::to_address(next));
        BOOST_RETHROW
    }
    BOOST_CATCH_END
    return dest;
}

和函数allocator_construct如下:

template<class A, class T, class V>
inline void allocator_construct(A&, T* p, const V& v)
{
    ::new((void*)p) T(v);
}
  • 有人可以帮助理解在 unitialized_copy 中调用 boost::allocator_construct(a, boost::to_address(dest), *first); 的目的以及为什么函数作者试图在 @ 中的第一个参数 A&amp; 处保留空参数987654325@.

感谢您的帮助。

【问题讨论】:

  • uninitialized_copy 表示将此数据复制到未初始化的数组中。为什么不应该调用construct
  • 作者没有尝试将参数留空,但函数中没有使用参数,所以最好不要给它起名字
  • 谢谢你的指导,现在我明白了调用 allocator_construct 来帮助在当前迭代器中构造对象。剩下的问题是什么,为什么参数 A& 留空?
  • 调用“boost::allocator_construct(a, boost::to_address(dest), *first);”是为了将来使用吗?谢谢大家

标签: c++ boost inline


【解决方案1】:

简短的回答是:此函数将值放入已分配但尚未初始化的内存中。这也是为什么这个特定的 allocator_construct 实现不使用分配器参数,但其他人可能会这样做。

为了解释为什么这很有用,请考虑std::vector,它具有要存储的类型和相应的分配器作为模板参数。它可以使用这些信息来管理自己的内存,允许它以块的形式分配内存,而不是为您添加的每个元素单独分配内存,这会慢得多。如果你复制一个值序列,它会首先确保有足够的内存可用,然后调用像uninitialized_copy这样的函数来做实际的工作。

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 2014-10-18
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多