Search code examples
c++boostinline

inline function with empty parameter


I'm studying on Boost library. Can someone help me understand below code.

/*!
    \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;
}

and the function allocator_construct as below:

template<class A, class T, class V>
inline void allocator_construct(A&, T* p, const V& v)
{
    ::new((void*)p) T(v);
}
  • Can some one help to understand the purpose of calling boost::allocator_construct(a, boost::to_address(dest), *first); in unitialized_copy and why the function author trying to leave empty param at first param A& in allocator_construct.

Thanks for your help.


Solution

  • The short answer is: this function puts values in memory that has already been allocated, but not yet initialized. That's also why this particular allocator_construct implementation does not use the allocator parameter, but others probably do.

    For an explanation of why this is useful, consider std::vector, which has both the type to be stored and a corresponding allocator as template parameters. It can use this information to manage its own memory, allowing it to allocate memory in chunks instead of separately for every element you add, which would be much slower. If you copy a sequence of values, it will first ensure that enough memory is available, then call a function like uninitialized_copy to do the actual work.