Function dual to std::move?

♀尐吖头ヾ 提交于 2019-12-29 09:05:43

问题


Let's assume I have a class with only one constructor:

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

  SomeBigClass
};

In most places the constructor is called on temporaries but in one place I need to make an explicit copy of BigClass because it is not a temporary and will be used multiple times in a loop:

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

Is there any function "dual" to std::move in C++11 or C++14 that would replace make_a_copy above ?

Edit: Some clarifications.


回答1:


Why can't you just copy the BigClass object?

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

This makes a temporary BigClass that is then moved into the T




回答2:


It's not hard to write:

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

There might be a standard function that happens to do that by accident when called with one argument, but there isn't one designed for this unusual pattern.




回答3:


If you can manipulate T you could template the constructor.

#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;
}

Prints

B moved (3)
B copied (4)

As far as I understand reference collapsing you should come out with a constructor A(B&) forwarding to the copy constructor of B and a A(B&&) forwarding to the move constructor of B.



来源:https://stackoverflow.com/questions/17497801/function-dual-to-stdmove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!