相关疑难解决方法(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
查看次数

copy elision:在return语句中使用三元表达式时调用未调用的构造函数?

请考虑以下示例:

#include <cstdio>

class object
{
public:
    object()
    {
        printf("constructor\n");
    }

    object(const object &)
    {
        printf("copy constructor\n");
    }

    object(object &&)
    {
        printf("move constructor\n");
    }
};

static object create_object()
{
    object a;
    object b;

    volatile int i = 1;

// With #if 0, object's copy constructor is called; otherwise, its move constructor.
#if 0
    if (i)
        return b; // moves because of the copy elision rules
    else
        return a; // moves because of the copy elision rules
#else
    // Seems equivalent …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

9
推荐指数
1
解决办法
791
查看次数