function template
<memory>

std::uninitialized_copy_n

template <class InputIterator, class Size, class ForwardIterator>  ForwardIterator uninitialized_copy_n ( InputIterator first, Size n,                                         ForwardIterator result );
Copy block of memory
Constructs copies of the n first elements of the array pointed by first into a range beginning at result and returns an iterator to the last element in the destination range.

Unlike algorithm copy_n, uninitialized_copy_n constructs the objects in-place, instead of just copying them. This allows to obtain fully constructed copies of the elements into a range of uninitialized memory, such as a memory block obtained by a call to get_temporary_buffer or malloc.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
template<class InputIterator, class Size, class ForwardIterator>
  ForwardIterator uninitialized_copy_n ( InputIterator first, Size n, ForwardIterator result )
{
  for (; n>0; ++result, ++first, --n)
    new (static_cast<void*>(&*result))
      typename iterator_traits<ForwardIterator>::value_type(*first);
  return result;
}

Parameters

first
Forward iterator to the initial position in an uninitialized sequence of at least n elements.
n
Number of elements to copy
Size is expected to be a numeric type.
result
Output iterator to the initial position in the uninitialized destination sequence. This shall not point to any element in the range [first,first+n).

Return value

An iterator to the last element of the destination sequence where elements have been copied.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// uninitialized_copy_n example
#include <iostream>
#include <memory>
#include <string>

int main () {
  std::string numbers[] = {"one","two","three"};

  // get block of uninitialized memory:
  std::pair <std::string*,std::ptrdiff_t> result = std::get_temporary_buffer<std::string>(3);

  if (result.second>0) {
    std::uninitialized_copy_n ( numbers, result.second, result.first );

    for (int i=0; i<result.second; i++)
      std::cout << result.first[i] << ' ';
    std::cout << '\n';

    std::return_temporary_buffer(result.first);
  }

  return 0;
}

Output:
one two three 


Complexity

Linear: constructs (copy construction) n objects.

See also