mirror of
https://gitlab.com/libeigen/eigen.git
synced 2026-04-10 11:34:33 +08:00
45 lines
1.4 KiB
Plaintext
45 lines
1.4 KiB
Plaintext
namespace Eigen {
|
|
|
|
/** \eigenManualPage TopicPassingByValue Passing Eigen objects by value to functions
|
|
|
|
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.
|
|
|
|
\note If you are compiling in C++17 mode with a sufficiently recent compiler (GCC >= 7, Clang >= 5, MSVC >= 19.12),
|
|
the alignment issues described below are handled automatically by the compiler, and passing %Eigen objects by value
|
|
is safe (though still less efficient than passing by const reference).
|
|
|
|
With pre-C++17 compilers, 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.
|
|
|
|
For example, a function like this, where \c v is passed by value:
|
|
|
|
\code
|
|
void my_function(Eigen::Vector2d v);
|
|
\endcode
|
|
|
|
needs to be rewritten as follows, passing \c v by const reference:
|
|
|
|
\code
|
|
void my_function(const Eigen::Vector2d& v);
|
|
\endcode
|
|
|
|
Likewise if you have a class having an %Eigen object as member:
|
|
|
|
\code
|
|
struct Foo
|
|
{
|
|
Eigen::Vector2d v;
|
|
};
|
|
void my_function(Foo v);
|
|
\endcode
|
|
|
|
This function also needs to be rewritten like this:
|
|
\code
|
|
void my_function(const Foo& v);
|
|
\endcode
|
|
|
|
Note that on the other hand, there is no problem with functions that return objects by value.
|
|
|
|
*/
|
|
|
|
}
|