Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 1 | namespace Eigen { |
| 2 | |
Gael Guennebaud | 93ee82b | 2013-01-05 16:37:11 +0100 | [diff] [blame] | 3 | /** \eigenManualPage TopicPassingByValue Passing Eigen objects by value to functions |
Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 4 | |
| 5 | Passing objects by value is almost always a very bad idea in C++, as this means useless copies, and one should pass them by reference instead. |
| 6 | |
Gael Guennebaud | 57acb05 | 2016-12-11 22:45:32 +0100 | [diff] [blame] | 7 | With %Eigen, this is even more important: passing \ref TopicFixedSizeVectorizable "fixed-size vectorizable Eigen objects" by value is not only inefficient, it can be illegal or make your program crash! And the reason is that these %Eigen objects have alignment modifiers that aren't respected when they are passed by value. |
Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 8 | |
Gael Guennebaud | 57acb05 | 2016-12-11 22:45:32 +0100 | [diff] [blame] | 9 | For example, a function like this, where \c v is passed by value: |
Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 10 | |
| 11 | \code |
| 12 | void my_function(Eigen::Vector2d v); |
| 13 | \endcode |
| 14 | |
Gael Guennebaud | 57acb05 | 2016-12-11 22:45:32 +0100 | [diff] [blame] | 15 | needs to be rewritten as follows, passing \c v by const reference: |
Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 16 | |
| 17 | \code |
| 18 | void my_function(const Eigen::Vector2d& v); |
| 19 | \endcode |
| 20 | |
Gael Guennebaud | 57acb05 | 2016-12-11 22:45:32 +0100 | [diff] [blame] | 21 | Likewise if you have a class having an %Eigen object as member: |
Benoit Jacob | 294f5f1 | 2009-01-12 14:41:12 +0000 | [diff] [blame] | 22 | |
| 23 | \code |
| 24 | struct Foo |
| 25 | { |
| 26 | Eigen::Vector2d v; |
| 27 | }; |
| 28 | void my_function(Foo v); |
| 29 | \endcode |
| 30 | |
| 31 | This function also needs to be rewritten like this: |
| 32 | \code |
| 33 | void my_function(const Foo& v); |
| 34 | \endcode |
| 35 | |
| 36 | Note that on the other hand, there is no problem with functions that return objects by value. |
| 37 | |
| 38 | */ |
| 39 | |
| 40 | } |