带空参数的内联函数
inline function with empty parameter
我正在研究 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);
的目的以及为什么该函数作者试图在 allocator_construct
. 中的第一个参数 A&
处保留空参数
感谢您的帮助。
简短的回答是:此函数将值放入已分配但尚未初始化的内存中。这也是为什么这个特定的 allocator_construct
实现不使用分配器参数,但其他人可能使用的原因。
为了解释为什么这是有用的,请考虑 std::vector
,它具有要存储的类型和相应的分配器作为模板参数。它可以使用此信息来管理自己的内存,允许它以块的形式分配内存,而不是为您添加的每个元素单独分配内存,这样会慢得多。如果您复制一系列值,它会首先确保有足够的内存可用,然后调用 uninitialized_copy
之类的函数来完成实际工作。
我正在研究 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);
的目的以及为什么该函数作者试图在allocator_construct
. 中的第一个参数
A&
处保留空参数
感谢您的帮助。
简短的回答是:此函数将值放入已分配但尚未初始化的内存中。这也是为什么这个特定的 allocator_construct
实现不使用分配器参数,但其他人可能使用的原因。
为了解释为什么这是有用的,请考虑 std::vector
,它具有要存储的类型和相应的分配器作为模板参数。它可以使用此信息来管理自己的内存,允许它以块的形式分配内存,而不是为您添加的每个元素单独分配内存,这样会慢得多。如果您复制一系列值,它会首先确保有足够的内存可用,然后调用 uninitialized_copy
之类的函数来完成实际工作。