I have been surprised to find that boost::multi_array seems to allocate its initial elements differently from, say, std::vector. It does not seem to fill each element with a unique element (using its default value or default constructor). I'm having trouble finding more information about this.
Is there a way to make the multi_array fill itself with a unique object at each element?
For example, consider the following:
static int num = 0;
struct A {
int n;
A() : n((::num)++) {
std::cout << "A()" << std::endl;
}
virtual ~A() {}
void print() {
std::cout << "n=" << n << std::endl;
}
};
int main() {
std::cout << "vector:" << std::endl;
std::vector<A> v(3);
for (auto x : v) {
x.print();
}
std::cout << "multi:" << std::endl;
boost::multi_array<A, 2> m(boost::extents[2][2]);
for (auto x : m) {
for (auto y : x) {
y.print();
}
}
}
This results in the output:
vector:
A()
A()
A()
n=0
n=1
n=2
multi:
A()
n=3
n=3
n=3
n=3
Why is the constructor called only once for the multi_array? How can the multi_array be "filled out" with unique objects (using A's default constructor)?
Aucun commentaire:
Enregistrer un commentaire