Boost logo

Boost Users :

Subject: [Boost-users] Minimal vector initialization
From: Henrik Vallgren (henrik.vallgren_at_[hidden])
Date: 2012-04-13 04:29:35


I'm proposing a small boost library:

struct minimal_init {};

template <typename T>
struct minimal_constructible : public T
{
   minimal_constructible() : T(minimal_init()) {}
};

The purpose of this is to enable vectors of simple structs (containing only POD members)
to have resize calling a do-nothing constructor. Let's say that I have a loop that I'd like to
calculate in parallel:

struct Dummy
{
  Dummy(int a_=0) : a(a_) {}
  Dummy(const minimal_init &) {} // Without a v-table, this shouldn't need to touch any part of the created object?

  int a;
};

void foo()
{
  #define N 100
  std::vector<minimal_constructible<Dummy> > data;

  data.resize(N);
  #pragma omp parallel for
  for (size_t i=0;i<N;++i)
    data[i].a=i;
}

Using reserve+push_back is unlikely to create a properly sorted vector.

Ideally, we'd add a resize member to std::vector that takes a template T2 that is different
from T, just like emplace_back does, but that won't happen soon.

I'll probably want to add a few things to make minimal_constructible<T> behave more
like a T, but I really liked the idea of a five line boost library ;)

Good idea, or not?

Thanks in advance,
Henrik



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net