【发布时间】:2022-12-23 00:41:40
【问题描述】:
The Eigen3 documentation warns against passing Eigen objects by value, 但它们仅指用作函数参数的对象。
假设我使用的是 Eigen 3.4.0 和 C++20。如果我有一个带有 Eigen 成员的 struct,这是否意味着我不能 std::move 在构造函数中按值传递?我是否需要按引用传递并复制对象?或者这是由现代移动语义以某种方式处理的?
如果我不能在构造函数中使用 std::move Eigen 对象,这是否意味着我应该明确地从我的结构中删除移动构造函数?
例如,
#include <utility>
#include <Eigen/Core>
struct Node {
Eigen::Vector3d position;
double temperature;
// is this constructor safe to use?
Node(Eigen::Vector3d position_, const double temperature_)
: position(std::move(position_)), temperature(temperature_) {}
// or must it be this?
Node(const Eigen::Vector3d& position_, const double temperature_)
: position(position_), temperature(temperature_) {}
// also, should move-constructors be explicitly deleted?
Node(Node&&) = delete;
Node& operator=(Node&&) = delete;
};
【问题讨论】:
-
您是否认为构造函数参数不是函数参数(它是),或者它没有被复制(它是)?
-
从第一个构造函数中没有任何好处,你为什么会喜欢它?通过引用传递并让 Eigen 复制构造函数执行它的操作。你不需要对移动语义做任何事情,
Vector3d有固定的分配,std::move没有任何好处——它对动态分配的对象很有用