Reputation: 4093
I want to make a Boost Matrix as an attribute of my class Adsorbate
. I know beforehand that it will be (3,2). I want to do:
#include <boost/numeric/ublas/matrix.hpp>
using namespace boost::numeric::ublas;
class Adsorbate {
matrix<double> m(3,2);
};
so that the compiler knows the size of the attribute m
and thus my class Adsorbate
. This way, I can make a pointer array of 200 of them:
Adsorbate * adsorbates = (Adsorbate *) malloc(200 * sizeof(Adsorbate));
How can I do this?
Upvotes: 1
Views: 332
Reputation: 1242
With regards to how to create an array of matrices, you are asking how to create a C array for a C++ data structure. Calling malloc will not correctly initialize the matrices in the array, nor calling "free" will deallocate dynamic memory if instances of ublas::matrix uses it, both failure to initialize an instance and failure to destroy it are severe bugs because things might seem to work, depending on the contents of the raw memory it can be all zeroes or something the application can handle, but it can also be be garbage that lead to catastrophic failures. Malloc will only give back the memory for instances, but internally, an instance of Adsorbate which has an instance of ublas::matrix might think it has valid pointers to memory or whatever.
To properly initialize the individual members of the array, Adsorbate *adsorbates = new Adsorbate[200];
Will use the default constructor for all the Adsorbate instances.
You can make it so that the default constructor of Adsorbate constructs its member m
with 3,2:
struct Adsorbate {
Adsorbate(): m{3, 2}, ... orther instance initializations here ... { ...arbitrary constructor code here.... }
...
}
Arrays are not advised. The advised way is to create an std::vector<Adsorbate>
. It might seem more complicated to use std::vector but it isn't, it will keep you from doing apparently simpler things that are potentially catastrophic unbeknownst to you.
If you insist on using naked arrays make sure to delete[]
an array instead of delete
. The difference is that delete
calls only the destructor of one element.
Upvotes: 2
Reputation: 76240
Just initialize it in the constructor:
class Adsorbate {
private:
matrix<double> m;
public:
Adsorbate() : m(3, 2) {}
// ...
};
Also if you want to create an array of 200 Adsorbate
, use std::vector
:
std::vector<Adsorbate> adsorbates(200);
Upvotes: 2