Re: Initializing arrays of objects
On Oct 21, 1:07 am, "Cristiano" <cristiano...@NSquipo.it> wrote:
I'm trying to compile this code:
template <typename T> class matrix
{
private:
class row
{
public:
T *data;
row(int n) {data = new T[n];};
...
} *rdata;
int rows, cols;
public:
matrix(int r, int c) { rows = r; cols = c; rdata = new row[r](c); };
...
but I get:
'Target of operator new()' : array initialization needs curly braces
and
'new' : 'matrix<T>::row' no default constructor to initialize arrays of
objects.
Any way to fix the problem?
The obvious answer is to use std::vector:
std::vector<row> rdata;
If you do, be sure to provide an appropriate copy constructor
and assignment operator, however. And you're likely to get a
lot more allocations than desired, because of temporary objects.
Alternatively, you can use the same technique used in
std::vector: separate allocation and initialization. Something
like:
rdata = static_cast< row* >( operator new( sizeof(row) * r ));
for ( size_t i = 0 ; i < r ; ++ i ) {
new ( rdata + i ) row( c ) ;
}
If you do this, you'll also have to use a similar technique in
the destructor, explicitly calling delete for each element, then
calling the operator delete function to free the memory.
You might want to consider a different approach:
std::vector< T > data ;
matrix( int r, int c ) : rows( r ), cols( c ), data( r * c ) {}
and then calculating the index in your operator[] or whatever.
--
James Kanze