Search code examples
c++fillinitialization

std::fill_n on array of non-PODs possible for first initializing?


is it possible to use std::fill to initialize an array of non-POD types?

The documentation says that std::fill uses operator= to initialize the array not placement copy construction. The assignment operator, however, does not really have a chance to free any current memory when it is called on an uninitialized space, as far as I can see.

Example:

struct NonPod
{
    std::string myStr;
};

NonPod arr[10];
NonPod prototype;
NonPod * ptr = &arr[0];
std::fill_n(ptr, 10, prototype);

Solution

  • You're looking for std::uninitialized_fill_n from the memory header, not std::fill_n from the algorithm header.

    Beware, however! Your code does not take alignment or padding into consideration -- consider using std::alignment_of, or the suitable boost replacement on platforms where it isn't available.