Question

I was reading the TC++PL about the raw_storage_iterator component. Using this component we get performance benefit as it avoids the assignment(more expensive) and uses copy construction. It looked to me that it should be used in the sequence/container where we could have significant number of elements and hence number of assignment calls can be great impact.

Theoretically its clear and it looked to me that this component is useful for container type classes. However I would like to understand where we should use this component(with practical examples) in bit details to get its performance benefit?

Was it helpful?

Solution

Over at cppreference there is sample code.

You can allocate aligned blocks of uninitialized memory through a number of mechanisms. Cppreferences uses std::get_temporary_buffer<T> to allocate such a buffer.

You can then make a pointer to these elements. The pointer's type is a bit misleading, because it isn't a pointer to a valid T, but rather to a block of memory that is suitable for constructing a T.

The std::raw_storage_iterator can be populated with that T* and told to output to it. You can then feed that iterator to an algorithm that expects a conventional output iterator, and things go smoothly.

If you tried to do this without the raw_storage_iterator, you'd be assigning to a non-constructed T, which is undefined behavior. As an alternative, you could construct the T's before outputting to them -- but that is wasteful, as it constructs the object twice.

The basic idea is to allow use of uninitialized output buffers with near perfect efficiency in standard algorithms. It isn't something you should be using outside of some serious code microoptimization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top