gpt4 book ai didi

c++ - Eigen 中的 move 语义

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:23 25 4
gpt4 key购买 nike

我有几个关于 Eigen 的问题:

  1. 有谁知道近期是否有计划在 Eigen 中支持 move 语义?在 Eigen3 网页的 TODO 列表中找不到任何内容。现在我正在使用 swap 技巧来摆脱临时对象,比如

    MatrixXd foo()
    {
    MatrixXd huge_matrix(N,N); // size N x N where N is quite large
    // do something here with huge_matrix
    return huge_matrix;
    }

    MatrixXd A(N, N);
    A.swap(foo());

    我非常想用 C++11 风格编写上面的 swap

    A = foo();

    并且不必担心 foo() 返回的临时值。

  2. C++98/C++03 编译器可以优化代码 A = foo(); 来摆脱这个临时问题吗?或者最安全的选择是使用 swap()

最佳答案

Copy elision会做的很好。即使是 C++03 编译器也会省略临时文件。
特别是,对于此代码,NRVO(命名返回值优化)将

MatrixXd foo()
{
MatrixXd huge_matrix(N,N);
return huge_matrix;
}

MatrixXd A = foo();

A 内部构造 huge_matrix。 C++03标准在[class.copy]/15中规定:

This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):

  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy operation can be omitted by constructing the automatic object directly into the function’s return value
  • when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy

关于c++ - Eigen 中的 move 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com