On Mar 21, 11:35 am, Jason McKesson<
jmckes...@gmail.com> wrote:
> On Monday, March 19, 2012 11:35:35 PM UTC-7, henrikv wrote:
> > Hello group!
>
> > When writing parallel code, I often allocate a vector for results. I
> > allocate the complete vector with a single resize. What I'd like to do
> > is to tell the resize not to initialize the content, since this will
> > be overwritten anyway. I'd figure something like:
[snip]
> > Any thoughts on this?
> This looks more like an improper use of `std::vector` than anything that should be added to the specification.
>
> All you need to do is use `std::vector::reserve` to allocate as much space as you plan to use. Then use `emplace_back` to construct each addition to the `vector` in-place.
There are at least two situations I can think of, where it would be
*very* useful to be able to initialize or resize a vector of PODs such
that the newly allocated elements will have no initialization
performed. (I'm ambivalent as to the exact mechanics Henrik
proposed.)
Case 1) Interfacing with old (C?) code that will initialize a
contiguous block of memory in-place. One can't always expect that
existing code can be rewritten to take a vector and call push_back or
emplace_back on it.
E.g., supposing the existence of something called std::no_initialize
(whatever that might be)
// some old 3rd-party library function; maybe it calls fread()?
extern "C" initialize_mem(size_t sz, int * mem);
vector<int> ints(42, std::no_initialize);
initialize_mem(ints.size(), ints.data());
Case 2) When it is necessary (or at least, easiest) to initialize the
elements in an order other than the consecutive forward traversal you
get with repeated calls to push_back or emplace_back. Consider
setting up a reverse look-up table for instance:
void make_reverse_lookup(const vector<int> & lut, vector<int> &
revlut)
{
// Pre-condition: the contents of 'lut' are the integers
// 0 through lut.size() - 1 in some arbitrary order.
int n = lut.size();
revlut.resize(n, std::no_initialize);
for (int i = 0; i< n; ++i)
revlut[lut[i]] = i;
}
- Kevin B. McCarty