Boost logo

Ublas :

From: Sebastian Gesemann (s.gesemann_at_[hidden])
Date: 2008-02-18 05:35:00


On Feb 12, 2008 5:51 PM, Benny Buerger <bbuerger_at_[hidden]> wrote:
> Here is a short example.
>
> class X
> {
> int sizex, sizey;
> void init();
> ublas::matrix<double> mat1;
> }
>
> X::X()
> {
> sizex=3;
> sizey=4;
> }
>
> void X::init()
> {
> mat1 = ublas::matrix<double>(sizex,sizey);
> }
>
> Is mat1 always defined after calling init() ?

Since mat1 is a member of X it is always constructed when an object of
class X is constructed. Either via an initializer list a la

X::X() : sizex(3), sizey(4), mat1(sizex,sizey) {}

or by calling the default c'tor implicitely which is what is happening
in your case, actually. Before you assign 3 and 4 to sizex and sizey,
the mat1 object is already constructed. in X::init() you could also do
something like this:

X::init() { mat1.resize(sizex,sizey,false); }

This makes sense in case you want to delay the memory allocation for
the matrix' elements as opposed to the initializer list alternative.
I'd prefer this over your mat1=matrix<double>(sizex,sizey) because
it's probably more efficient. If I had to guess what exactly happens
with your version I'd say:
- you're creating a temporary matrix object on the stack which
allocates memory on the heap for the matrix' elements
- the assignment operator lets the mat1 object also allocate 3x4
elements of its own. The elements of the temporary matrix are then
"copied into" your mat1 object. (*)
- the temporary matrix is then destroyed.

(* Even though the matrix (or its embedded container) object usually
stores a pointer to an element array it has *value semantics*)

Grüße,
Sebastian