MTL 4: Why Not Using Shallow Copy in Numerical Software
// File: shallow_copy_problems_type.cpp #include <iostream> #include <boost/numeric/mtl/mtl.hpp> using namespace mtl; int main(int, char**) { dense2D<double> A(3, 3), B(3, 3); dense2D<float> C(3, 3); A= 4.0; B= A; // Create an alias B*= 2.0; // Changes also A C= A; // Copies the values C*= 2.0; // A is unaffected return 0; }
A= B; // Aliasing of A and B A= 1.0 * B; // A and B are independent
A= B; // (Potential) shallow copy copy(B, A); // Deep copy
We refrain from this approach because this syntax does not correspond to the mathematical literature and more importantly we cannot be sure that all users of a library will replace assignments by copy.
// File: shallow_copy_problems_const.cpp #include <iostream> #include <boost/numeric/mtl/mtl.hpp> using namespace mtl; template <typename Matrix> void f2(Matrix& C) { C= 5.0; } // Undermine const-ness of function argument template <typename Matrix> double f(const Matrix& A) { Matrix B; B= A; f2(B); return frobenius_norm(A); } int main(int, char**) { dense2D<double> A(3, 3); A= 4.0; double alpha= f(A); // A is changed now! std::cout << alpha << "\n"; return 0; }
After calling f, A is modified despite it was passed as const argument and the const-ness was not even casted away.
Return to Copying in MTL4 Table of Content Proceed to Addicted to peak performance
Why Not Using Shallow Copy in Numerical Software -- MTL 4 -- Peter Gottschling and Andrew Lumsdaine
-- Gen. with
rev. 7542
on 7 Apr 2011 by doxygen 1.5.9 -- © 2010 by SimuNova UG.