function template
<memory>

std::get_temporary_buffer

template <class T>
  pair <T*,ptrdiff_t> get_temporary_buffer ( ptrdiff_t n );
template <class T>
  pair <T*,ptrdiff_t> get_temporary_buffer ( ptrdiff_t n ) noexcept;
Get block of temporary memory
Requests a temporary block of storage to contain up to n elements of type T temporarily.

The block of storage is aligned apropriately to contain elements of type T if T has a fundamental alignment, although it is left uninitialized (no object is constructed).

This function is specifically designed to obtain memory of temporary nature (such as for the operations of an algorithm). Once the memory block is not needed anymore, it shall be released by calling return_temporary_buffer.

Notice that the actual size of the buffer returned may be smaller than requested (the actual size is indicated as part of the return value).

Parameters

n
Number of elements of type T for which temporary memory is requested.
ptrdiff_t is an integral type.

Return value

On success, the function returns a pair object with its first element containing a pointer to the first element in the block, and the second element its size, in terms of number of elements of type T that it can hold.

If the storage cannot be allocated, the pair contains a null pointer as first and a value of zero as second.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// get/return_temporary_buffer example
#include <iostream>
#include <memory>
#include <algorithm>

int main () {
  int numbers[] = {30,50,10,20,60,40};

  // use temporary buffer to sort and show the numbers:
  std::pair <int*,std::ptrdiff_t> result = std::get_temporary_buffer<int>(6);
  if (result.second>0)
  {
    std::uninitialized_copy (numbers,numbers+result.second,result.first);
    std::sort (result.first,result.first+result.second);
    std::cout << "sorted numbers  : ";
    for (int i=0;i<result.second;i++)
      std::cout << result.first[i] << " ";
    std::cout << '\n';
    std::return_temporary_buffer (result.first);
  }

  // show original numbers:
  std::cout << "unsorted numbers: ";
  for (int i=0;i<6;i++)
    std::cout << numbers[i] << " ";
  std::cout << '\n';
  return 0;
}


Possible output:

sorted numbers  : 10 20 30 40 50 60
unsorted numbers: 30 50 10 20 60 40

See also