|Re: [eigen] Why do const accessors return by value?|
[ Thread Index |
| More lists.tuxfamily.org/eigen Archives
- To: eigen@xxxxxxxxxxxxxxxxxxx
- Subject: Re: [eigen] Why do const accessors return by value?
- From: Benoit Jacob <jacob.benoit.1@xxxxxxxxx>
- Date: Tue, 31 Mar 2009 22:04:18 +0200
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=domainkey-signature:mime-version:received:in-reply-to:references :date:message-id:subject:from:to:content-type :content-transfer-encoding; bh=lyrJEvLug2H+NCI6Oq9CNcvuR1EUnY2Hi9TDUENGge8=; b=fVDXvw7VICbw/DF30L6Y3FPv0rOM4/GQMtS02F0vo1LBv7Go/fZsv9w0TSC4K0Se+N WIErSxL7yXBj8crX1faQJaEJ/BkVvNLlw38I/ycZYbgNudVyMs1EwMb0v2efLtIyyDGS 2gza9q0YIVZEcFf7i3n6i2laZAZIiYiPd4tIM=
- Domainkey-signature: a=rsa-sha1; c=nofws; d=gmail.com; s=gamma; h=mime-version:in-reply-to:references:date:message-id:subject:from:to :content-type:content-transfer-encoding; b=I7JucL6yqONKJeufbOjRlSX1oTpOglgs88YhbBDREnYgA9tN/mz02zhiDFJFdUSF6A vn78oC84rQHbadmlTbo1cgbkz2QCaXlyDYEl6vbsArnOKvGO+7ovdkszjuU1xjIb2Tdt JT/6WmpbwfEthXyJZOYngRlX5MzJzFv7i0uSE=
2009/3/31 Patrick Mihelich <patrick.mihelich@xxxxxxxxx>:
> Hi again,
> Currently all of the MatrixBase const accessor functions return const
> Scalar, while the non-const version return (of course) Scalar&. Is there a
> rationale for returning by value in the const versions instead of const
Yes, in fact we have simply no choice. A MatrixBase may be any
expression. As soon as an expression represents a nontrivial
computation (like a sum of two matrices) there is no way that coeff()
could return a reference : a reference to what? the result isn't
stored permanently in memory.
> I don't like this inconsistent behavior. Sometimes I want to get a
> pointer to a chunk of memory in a Matrix so I can pass it to some low-level
> function, like foo( &mat(r, c) ).
Above you were talking about MatrixBase; now with Matrix it's
different, indeed the coefficients do exist in memory, and if you look
at the Matrix class, the coeff() methods do return const references,
exactly like you want!
If you have a MatrixBase that happens to be a Matrix, you can always
use the derived() method to get the matrix:
void foo(const MatrixBase& m)
float *ptr = &(m.derived().coeff(i,j));
in fact derived() just casts 'this' to a Matrix pointer, and indirects.
> This breaks when mat is a const type like
> const Matrix&. I can also imagine wanting to use Eigen matrices with types
> that are not trivially cheap to copy (arbitrary precision types, for
> example), when returning by value may result in an unwanted copy.
That's another issue. But the above-mentioned fact that xpressions
have no choice but to return by value, is unavoidable. So I think that
the best solution then, is that the "heavy numeric types" in question
be endowed with a copy-on-write mechanism so that these copies become