Re: How to return a reference, when I really need it
"BlackLight" <blacklight86@gmail.com>
where Matrix is a class I wrote for matrices management, and Vector is
another class (fundamentally a wrapping around vector<float>
float will very likely burn you or the users... Use double unless absolutely
sure precision and roundings are accounted for everywhere.
Also, are you sure you want to write yet-another-homegrown matrix class
instead of using an existing, ready with all your functions and passed years
of testing and reviews?
And do some from scratch and top of your head, instead at least reading a
couple of such implementations? On the way learning the answers to this
question and many others you will encounter shortly.
Vector Matrix::operator[] (size_t i) throw() {
if (i >= rows)
throw InvalidMatrixIndexException();
vector<float> row;
for (int j=0; j < cols; j++)
row.push_back(matrix[i][j]);
return Vector(row);
}
I wrote
for doing cool mathematical tricks, like sums, scalar products, norms
etc.). This is the actual implementation, but I would like to return a
reference to the Vector object, i.e. Vector& Matrix::operator[] (...).
I need it to do tricks like
Matrix A;
A[0][0] = 1.0;
or something like that, and this is not possible returning the Vector
object as a value.
yeah, returning a vector, and by value is (on top of being way inefficient)
leaves you with such code compiling, then surprise the user.
But if I declare a local Vector object and I return
its reference, I've got a problem as returning the reference of a
local variable.
Indeed, to return a vector by ref you need a stable vector, i.e. switch
internal representation to vector< vector< T > >. That would certainly mean
oblugation to resize all the row-vectors, separate mem-allocation, losing
locality and so on.
Alternatively you may return a pointer instead of vector: & matrix[i][0],
provided the memory layout is compatible -- then op [] works as expected,
though you lose features of vector, and gain some danger of pointers.
Or you can return a proxy-vector class by value that has op[] and captures
enough info to find way to its source. ...
IIRC Matthew Wilson's Imperfect C++ has a comprehensive section on creating
wrappers for multi-dim arrays and the zillion of problems it brings.
And the topic must have good coverage in general.