xref: /aosp_15_r20/external/eigen/doc/PassingByValue.dox (revision bf2c37156dfe67e5dfebd6d394bad8b2ab5804d4)
1*bf2c3715SXin Linamespace Eigen {
2*bf2c3715SXin Li
3*bf2c3715SXin Li/** \eigenManualPage TopicPassingByValue Passing Eigen objects by value to functions
4*bf2c3715SXin Li
5*bf2c3715SXin LiPassing 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*bf2c3715SXin Li
7*bf2c3715SXin LiWith %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.
8*bf2c3715SXin Li
9*bf2c3715SXin LiFor example, a function like this, where \c v is passed by value:
10*bf2c3715SXin Li
11*bf2c3715SXin Li\code
12*bf2c3715SXin Livoid my_function(Eigen::Vector2d v);
13*bf2c3715SXin Li\endcode
14*bf2c3715SXin Li
15*bf2c3715SXin Lineeds to be rewritten as follows, passing \c v by const reference:
16*bf2c3715SXin Li
17*bf2c3715SXin Li\code
18*bf2c3715SXin Livoid my_function(const Eigen::Vector2d& v);
19*bf2c3715SXin Li\endcode
20*bf2c3715SXin Li
21*bf2c3715SXin LiLikewise if you have a class having an %Eigen object as member:
22*bf2c3715SXin Li
23*bf2c3715SXin Li\code
24*bf2c3715SXin Listruct Foo
25*bf2c3715SXin Li{
26*bf2c3715SXin Li  Eigen::Vector2d v;
27*bf2c3715SXin Li};
28*bf2c3715SXin Livoid my_function(Foo v);
29*bf2c3715SXin Li\endcode
30*bf2c3715SXin Li
31*bf2c3715SXin LiThis function also needs to be rewritten like this:
32*bf2c3715SXin Li\code
33*bf2c3715SXin Livoid my_function(const Foo& v);
34*bf2c3715SXin Li\endcode
35*bf2c3715SXin Li
36*bf2c3715SXin LiNote that on the other hand, there is no problem with functions that return objects by value.
37*bf2c3715SXin Li
38*bf2c3715SXin Li*/
39*bf2c3715SXin Li
40*bf2c3715SXin Li}
41