相关疑难解决方法(0)

在多个return语句的情况下,返回`std :: move`是否合理?

我知道回归通常不是一个好主意std::move,即

bigObject foo() { bigObject result; /*...*/ return std::move(result); }
Run Code Online (Sandbox Code Playgroud)

而不是简单的

bigObject foo() { bigObject result; /*...*/ return result; }
Run Code Online (Sandbox Code Playgroud)

因为它妨碍了返回值优化.但是在具有多个不同回报的函数的情况下,特别是类似的东西

class bar {
  bigObject fixed_ret;
  bool use_fixed_ret;
  void prepare_object(bigObject&);
 public:
  bigObject foo() {
    if(use_fixed_ret)
      return fixed_ret;
     else{
      bigObject result;
      prepare_object(result);
      return result;
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

我认为在这样的函数中,正常的返回值优化是不可能的,所以投入是一个好主意

      return std::move(result);
Run Code Online (Sandbox Code Playgroud)

在这里,或者我应该做什么(IMO丑陋,但这是有争议的)

  bigObject foo() {
    bigObject result;
    if(use_fixed_ret)
      result = fixed_ret;
     else{
      prepare_object(result);
    }
    return result;
  }
Run Code Online (Sandbox Code Playgroud)

c++ move-semantics return-value-optimization c++11

22
推荐指数
1
解决办法
6569
查看次数

返回(大)对象时复制开销?

考虑以下两种简单的Matrix4x4 Identity方法的实现.

1:这个参数采用Matrix4x4参考作为参数,其中直接写入数据.

static void CreateIdentity(Matrix4x4& outMatrix) {
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            outMatrix[i][j] = i == j ? 1 : 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2:这个返回Matrix4x4而不进行任何输入.

static Matrix4x4 CreateIdentity() {
    Matrix4x4 outMatrix;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            outMatrix[i][j] = i == j ? 1 : 0;
        }
    }
    return outMatrix; …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

4
推荐指数
1
解决办法
406
查看次数