Topic: Fixed-size arrays
Author: tohoyn@janus.otol.fi (Tommi H|yn{l{nmaa)
Date: 8 Jan 1995 10:35:01 GMT Raw View
Does the new Standard C++ Library have a fixed-size array class?
I think it should because a fixed-size array class could replace the
unsafe C arrays in many places. Of course, a variable-size array
class could be used also but they need dynamic memory allocation, which
may be unnecessary. Because the size of a fixed-size array is known
compile-time it does not need any dynamic memory allocation. Therefore, it
would be as efficient as the standard C array if the index checks are
turned off.
Here is an example of what kind of class I mean:
template <class T, int size>
class fixed_array
{
public:
fixed_array()
{
// No dynamic allocation needed, because the array is allocated statically.
}
T& operator [] (int index)
{
assert( index >= 0 && index < size );
return data[index];
}
const T& operator [] (int index) const
{
assert( index >= 0 && index < size );
return data[index];
}
private:
T data[size];
};
Now the class fixed_array could be used like this:
int main
{
fixed_array<int, 10> numbers; // normally: int numbers[10];
int i;
for( i = 0; i < 10; i++ )
{
cout << "Give a number: ";
cin >> numbers[i];
}
...
}
However, the fixed_array class has some restrictions compared to the C-style
arrays:
- You can't take a subarray from it.
- If you want to write a function that has an argument whose type is an
fixed_array of arbitrary size, you have to use templates.
e.g.
You want to write a function that fills any fixed_array of type
int with a given number:
template <int size>
void fill(fixed_array<int, size> array, int number)
{
int index;
for( index = 0; index < size; index++ )
array[index] = number;
}
Tommi H yn l nmaa (7-bit ASCII: H|yn{l{nmaa)
Author: maxtal@physics.su.OZ.AU (John Max Skaller)
Date: Mon, 9 Jan 1995 03:49:17 GMT Raw View
In article <3eof4l$s3e@tethys.otol.fi> tohoyn@janus.otol.fi (Tommi H|yn{l{nmaa) writes:
>
>Does the new Standard C++ Library have a fixed-size array class?
No.
>I think it should because a fixed-size array class could replace the
>unsafe C arrays in many places.
I agree. In particular, it isn't possible to implement one
that can be initialised in a class if the type is
const, or
has no accessible default constructor
has no accessible assignment
and these cases could be handled by a Standard Library template.
AND/OR a language extension.
class X {
const int a[2];
X() : ???? {} // WOOPS
};
class Z { Z(int); };
class X {
Z a[2];
X() : ??? {} // WOOPS
};
class Q { void operator=(const Q&); }
class X {
Q a[2];
X() { a[0]=Q(); // WOOPS
}};
In general, there is no way to initialise an aggregate
in a mem-initialiser: member or base. I suggest:
X() : a={1,1} {}
for example (the usual initialisation syntax).
--
JOHN (MAX) SKALLER, INTERNET:maxtal@suphys.physics.su.oz.au
Maxtal Pty Ltd,
81A Glebe Point Rd, GLEBE Mem: SA IT/9/22,SC22/WG21
NSW 2037, AUSTRALIA Phone: 61-2-566-2189