c++ - 返回 Eigen::Ref 是否合法?

标签 c++ eigen eigen3

Eigen 的文档解释了如何将 Eigen::Ref 用作函数参数。将它也用作函数返回值是个好主意吗?

例如

class XyTracker : public XyListener {
 public:
  XyTracker() = default;
  XyTracker(XyTracker&&) = default;
  XyTracker& operator=(XyTracker&&) = default;

  const Eigen::Ref<const Eigen::ArrayXXd> Xs() const;
  const Eigen::Ref<const Eigen::ArrayXd> Ys() const;

  // XyListener
  void OnXy(const Eigen::VectorXd& x, double y) final;

 private:
  Eigen::ArrayXXd xs_;
  Eigen::ArrayXd ys_;
  Eigen::Index n_ = 0;
};

inline const Eigen::Ref<const Eigen::ArrayXXd> XyTracker::Xs() const {
  return xs_.topRows(n_);
}

inline const Eigen::Ref<const Eigen::ArrayXd> XyTracker::Ys() const {
  return ys_.head(n_);
}

最佳答案

正如评论中已经指出的那样,返回 Ref 对象没有任何问题,只要您确保您所引用的对象在您使用引用。

简化示例:

struct A {
    ArrayXXd xs;
    Ref<const ArrayXXd> Xs() const {
        return xs.topRows(5);  // works (when used properly)
    }
    Ref<const ArrayXXd> NotWorking() const {
        ArrayXXd foo = 2*xs;
        return foo.topRows(5); // compiles, but will give U.B.
};


// usage:
A a;
a.xs.setRandom(10,10);

Ref<const ArrayXXd> r1 = a.Xs();
// fine to use r1 here
a.xs.setRandom(20,20);
// from here on r1 will point to non-existing memory
// i.e., using r1 will be U.B.

U.B. (未定义的行为)示例基本上都是释放后使用,不幸的是,编译器几乎无法检测到,因此在使用 Eigen::Ref 时需要多加小心。 UB 可能意味着你的单元测试工作,虽然你的代码很糟糕,但突然在生产中你会遇到段错误......

关于c++ - 返回 Eigen::Ref 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401856/

相关文章:

c++ - 如何在虚幻引擎中使用第三方库 Eigen?

c++ - Eigen 对 Rows 模板的可变模板扩展有问题

c++ - 使用 Eigen 的性能比使用我自己的类更差

c++ - 为什么 Eigen 不解析内置符号? (所有,最后,seq,等等...)

c++ - 将代码从 Eigen2 移植到 Eigen3 时的奇怪行为

c++ - 无法使此代码在 MSVC 2015 和 GCC 7.3 之间交叉编译

字节不在文件中的 Python Unicode 解码错误

CMake找不到源码目录(安装Eigen)

c++ - 删除[]后剩余的堆数组的剩余元素

c++ - 在 C++ 中可视化 3D 条形图