Thursday, March 27, 2025

raw_storage_iterator

Overview
The output iterator raw_storage_iterator makes it possible for standard algorithms to store results in uninitialized memory.

Details
Regular iterators operate on a certain type of objects, which have already been constructed. A raw_storage_iterator wraps one of these regular iterators into a special output iterator which constructs objects at the location being pointed before being written.
Whenever the algorithm writes an object of type T to the dereferenced iterator, the object is copy-constructed into the location in the uninitialized storage pointed to by the iterator. 

Syntax
The syntax is as below. 
template< class OutputIterator,
          class T>
class raw_storage_iterator;

NameDescription
OutputIteratorUnderlying iterator type.
TType of objects to be constructed on each element location.

Members
 It defines following types.
member typedefinition
iterator_categoryoutput_iterator_tag
value_typevoid
difference_typevoid
pointervoid
referencevoid

Operation
An raw_storage_iterator as an output iterator supports operators *, ++, and =. 

 Functionality
Constructors
NameDescription
raw_storage_iterator( OutputIt  it)
Initializes the iterator to point to the same value as it points.

Overloaded operators
NameDescription
raw_storage_iterator & operator*()  Does nothing. Returns a reference to the object.
  1. raw_storage_iterator & operator++()
  2. raw_storage_iterator & operator++(int)
 Advances the iterator.
  1. Pre-increment. Returns the updated iterator.
  2. Post-increment. Returns the old value of the iterator.
raw_storage_iterator & operator=
(
const T& value)
Constructs a new object of type T at the location pointed by the iterator and initializes
its value to a copy of the argument used as right-hand side of the operator.

Example:
    string numbers[] = {"one", "two", "three", "four"};
    size_t sz = sizeof(numbers);
    char *buf = new char[sizeof(string)*sz];
    string *sbuf = reinterpret_cast<string*>(buf);

    auto last = copy(begin(numbers), end(numbers), 
      raw_storage_iterator<string*, string>(sbuf));

    //prints one two three four 
    for (auto itr = sbuf; itr != sbuf+sz; ++itr)
        cout << *itr  << " ";

    for (auto itr = sbuf; itr != sbuf+sz; ++itr)
        itr->~string();
    
   delete[] buf;



No comments:

Post a Comment