You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.7 KiB

  1. namespace Eigen {
  2. /** \page TopicPitfalls Common pitfalls
  3. \section TopicPitfalls_template_keyword Compilation error with template methods
  4. See this \link TopicTemplateKeyword page \endlink.
  5. \section TopicPitfalls_auto_keyword C++11 and the auto keyword
  6. In short: do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing. In particular, do not use the auto keyword as a replacement for a Matrix<> type. Here is an example:
  7. \code
  8. MatrixXd A, B;
  9. auto C = A*B;
  10. for(...) { ... w = C * v; ...}
  11. \endcode
  12. In this example, the type of C is not a MatrixXd but an abstract expression representing a matrix product and storing references to A and B. Therefore, the product of A*B will be carried out multiple times, once per iteration of the for loop. Moreover, if the coefficients of A or B change during the iteration, then C will evaluate to different values.
  13. Here is another example leading to a segfault:
  14. \code
  15. auto C = ((A+B).eval()).transpose();
  16. // do something with C
  17. \endcode
  18. The problem is that eval() returns a temporary object (in this case a MatrixXd) which is then referenced by the Transpose<> expression. However, this temporary is deleted right after the first line, and there the C expression reference a dead object. The same issue might occur when sub expressions are automatically evaluated by Eigen as in the following example:
  19. \code
  20. VectorXd u, v;
  21. auto C = u + (A*v).normalized();
  22. // do something with C
  23. \endcode
  24. where the normalized() method has to evaluate the expensive product A*v to avoid evaluating it twice. On the other hand, the following example is perfectly fine:
  25. \code
  26. auto C = (u + (A*v).normalized()).eval();
  27. \endcode
  28. In this case, C will be a regular VectorXd object.
  29. */
  30. }