Question

It seems that boost::multi_array<T, n> requires that T have a no-argument constructor. Consider the following example.

#include <boost/multi_array.hpp>

class ConstructorHasArguments {
    ConstructorHasArguments(int arg) {};
}

int main() {
    boost::multi_array<ConstructorHasArguments, 1> foo;
    return 0;
}

This results in a compile error.

no matching function for call to ‘ConstructorHasArguments::ConstructorHasArguments()

The problem is that, when the copy constructor for boost::multi_array<T,n> tries to allocate space for the copy, it attempts to call T(). I could, of course, add a no-argument constructor to my class. But what if I have a class for which a no-argument constructor doesn't make sense?

Is there a simple way to use boost::multi_array when T does not have a no-argument constructor?

Was it helpful?

Solution

It is not only the copy constructor - actually all constructors of boost::multiarray will call allocate_space(), which in turns invokes std::uninitialize_fill_n(base, allocated_elements_, T());. Therefore a constructor without argument is required here. I don't think there is a way to bypass it if you still want to use boost::multi_array. (I am referring to the source code of boost-1.46.0.)

An alternative may be like this: you allocate and initialize space by yourself. Then pass the address to boost::multi_array_ref. In this case you will have to manage the memory.

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