Eigen学习笔记16:按值传递Eigen对象

在C ++中,按值传递对象几乎总是一个非常糟糕的做法,因为这意味着无用的副本,最好通过引用传递它们。

使用Eigen时,这甚至更重要:按值传递fixed-size vectorizable Eigen types,不仅效率低下,而且可能是非法的,或者会使程序崩溃!原因是这些Eigen对象具有对齐修饰符,当按值传递它们时,这些修饰符 aren't respected

因此,例如,像这样的函数:

void my_function(Eigen :: Vector2d v);

需要重写如下,通过引用传递v:

void my_function(const Eigen :: Vector2d&v);
同样,如果您有一个将Eigen对象作为成员的类:
struct Foo
{
  Eigen::Vector2d v;
};
void my_function(Foo v);

此功能也需要这样重写:

void my_function(const Foo& v);


Note that on the other hand, there is no problem with functions that return objects by value.

你可能感兴趣的:(Eigen)