函数双重到std :: move?

时间:2013-07-05 22:50:41

标签: c++ c++11 move-semantics

假设我有一个只有一个构造函数的类:

class T {
 public:
  T(BigClass&& big) : big(std::move(big)) {}
  ...

  SomeBigClass
};

在大多数地方,构造函数是在temporaries上调用的,但是在一个地方我需要制作一个BigClass的显式副本,因为它不是一个临时的,并且会在循环中多次使用:

void foo(const BigClass& big) {
  while (...) {
    T t(std::make_a_copy(big));
    ...
  }
}

在C ++ 11或C ++ 14中,std::move是否有任何“双重”功能可以取代上面的make_a_copy?

修改:一些澄清。

3 个答案:

答案 0 :(得分:6)

为什么不能只复制BigClass对象?

void foo(const BigClass& big) {
  while (...) {
    T t{ BigClass(big) };
    ...
  }
}

这会使临时BigClass移入T

答案 1 :(得分:1)

写起来并不难:

template <typename T>
T make_temp(const T& x) { return x; }

当使用一个参数调用时,可能会有一个标准函数偶然发生这种情况,但没有一个针对这种不寻常的模式设计。

答案 2 :(得分:-1)

如果你可以操纵T,你可以模板化构造函数。

#include <iostream>
using namespace std;
class B
{
  int x;
public:
  B (int i) : x(i) { }
  B (B && b) : x(b.x) { cout << "B moved (" << x << ")" << endl; }
  B (B const  & b) : x(b.x)  { cout << "B copied (" << x << ")" << endl; }
};


class A
{
  B b;
public:
  template<typename TB>
  A (TB && init_b) : b(std::forward<TB &&>(init_b)) { }
};

B foo (void) { B x(3); return x; }


int main (void)
{
  A a1(foo());
  B b1(4);
  A a2(b1);
  return 0;
}

打印

  

B搬家(3)
  B复制(4)

据我所知,引用崩溃时,您应该使用构造函数A(B&)转发到B的复制构造函数,并转发A(B&&)移动构造函数{{1} }。

相关问题