Showing posts with label lessons learned. Show all posts
Showing posts with label lessons learned. Show all posts

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.