Namespaces
Variants
Views
Actions

std::get_temporary_buffer

From cppreference.com
< cpp‎ | memory
Revision as of 02:11, 26 June 2012 by P12 (Talk | contribs)

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
Dynamic memory management
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Allocators
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)



Uninitialized storage
(until C++20*)
get_temporary_buffer
(until C++20*)
 
Defined in header <memory>
template< class T >
std::pair< T*, std::ptrdiff_t > get_temporary_buffer( std::ptrdiff_t count )

Allocates storage sufficient to store up to count adjacent objects of type T. If there is insufficient memory for all count objects, allocates less than count, if possible.

Contents

Parameters

count - the number of objects to allocate

Return value

An std::pair holding a pointer to the beginning of the allocated storage and the number of objects that fit in the storage that was actually allocated (may be zero).

Exceptions

noexcept specification:  
noexcept
  

Example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <string>
 
int main()
{
    const std::string s[] = {"string", "1", "test", "..."};
    const auto p = std::get_temporary_buffer<std::string>(4);
    // requires that p.first is passed to return_temporary_buffer
    // (beware of early exit points and exceptions), or better use:
    std::unique_ptr<std::string, void(*)(std::string*)> on_exit(p.first,
    [](std::string* p)
    {
        std::cout << "returning temporary buffer...\n";
        std::return_temporary_buffer(p);
    });
 
    std::copy(s, s + p.second,
              std::raw_storage_iterator<std::string*, std::string>(p.first));
    // has same effect as: std::uninitialized_copy(s, s + p.second, p.first);
    // requires that each string in p is individually destroyed
    // (beware of early exit points and exceptions)
 
    std::copy(p.first, p.first + p.second,
              std::ostream_iterator<std::string>{std::cout, "\n"});
 
    std::for_each(p.first, p.first + p.second, [](std::string& e)
    {
        e.~basic_string<char>();
    }); // same as: std::destroy(p.first, p.first + p.second);
 
    // manually reclaim memory if unique_ptr-like technique is not used:
    // std::return_temporary_buffer(p.first);
}

Output:

string
1
test
...
returning temporary buffer...

See also

Template:cpp/memory/dcl list return temporary buffer