I'm using Boost to do some matrix algebra. I'm trying to understand if this optimization does anything. Original:
matrix<double> DoSomething(matrix<double> a, matrix<double> b)
{
return a + b; //for example
}
Optimization:
matrix<double>* DoSomething(matrix<double>* a, matrix<double>* b)
{
return *a + *b; //for example
}
Basically, I assumed that using pointers as the parameters and the return type would prevent copying a large object. After reading through the source code, I'm wondering if Boost ublas basically takes care of this. It seems like you're always dealing with a reference in Boost's code.
That's not an optimization. In fact, it's a disaster. Your "optimized" code returns a pointer to a temporary object that no longer exists when the function returns. If you try to fix this:
Well, look what you just did there. You just asked to create a copy, since your new matrix is copy-constructed from the temporary that results from summing
a
andb
. Worse, this code is now no longer exception safe and it's easy to screw up in the caller and not release the allocated matrix.So leave it alone. It's already optimized, and you can easily break it or make it worse.