function template
<memory>

std::uninitialized_copy

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

Unlike algorithm copy, uninitialized_copy 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
9
template<class InputIterator, class ForwardIterator>
  ForwardIterator uninitialized_copy ( InputIterator first, InputIterator last,
                                       ForwardIterator result )
{
  for (; first!=last; ++result, ++first)
    new (static_cast<void*>(&*result))
      typename iterator_traits<ForwardIterator>::value_type(*first);
  return result;
}


Parameters

first, last
Input iterators to the initial and final positions in a sequence to be copied. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
result
Output iterator to the initial position in the uninitialized destination sequence. This shall not point to any element in the range [first,last).

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 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 ( numbers, 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) as many objects as the distance between first and last.

See also