Thursday, August 21, 2008

Lessons Learned part 1.

I thought I would share some lessons learned while coding freemat. The first lesson is due to Samit.
#include 

class A {
int m_data;
public:
A(int m) : m_data(m) {std::cout << "Construct A: " << m_data << "\n";}
const int & value() const { return m_data;}
const A doubled() const {return A(2*m_data);}
~A() {std::cout << "Destruct A: " << m_data << "\n";}
};

int main() {
A x(5);
const int &y(x.doubled().doubled().value());
std::cout << "y = " << y << "\n";
return 0;
}

The result:

$ ./temp
Construct A: 5
Construct A: 10
Construct A: 20
Destruct A: 20
Destruct A: 10
y = 20
Destruct A: 5

Note that the temporary object "A" is destructed _before_ the const
ref to it's internals is used. So...

int main() {
A x(5);
const A &t(x.doubled().doubled());
const int &y(t.value());
std::cout << "y = " << y << "\n";
return 0;
}

yields:

$ g++ -o temp temp.cpp
$ ./temp
Construct A: 5
Construct A: 10
Construct A: 20
Destruct A: 10
y = 20
Destruct A: 20
Destruct A: 5

Yikes.

3 comments:

Eugene said...

It is meant to be:
#include iostream

but angle brackets got eaten by the "Blogger"...

Amber said...

My my

There was a lesson learnt in there.

But what was it?

(the way _I_ read it was: "pick up a book on C++ before using it to shoot yourself in the foot", but I might have missed an important clue)

Naresh said...

Hi,

I see that his blog isn't active since 2009 and also no new releases on FreeMat website. Is this project terminated? If so, could the developers spend a little bit of time on my following request. This might actually enable FreeMat to live on for ever.

Octave has excellent MATLAB compatibility and quite high MATLAB functionality. But, there is no GUI. So, no easy editing of scripts, no easy debugging , no "all things docked into one GUI"

FreeMat has a great GUI. The compatibility is great but is still catching with the functionality. A majority of functionality is missing / yet to be written.

Now, if only the FreeMat front-end works with an Octave backend then the dream is fulfilled. We have a nice GUI for doing all the cool things and still have all the compatibility and functionality powered by Octave.