Function dual to std::move?

后端 未结 3 785
刺人心
刺人心 2020-12-21 09:58

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

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

  SomeBigClass
};


        
相关标签:
3条回答
  • 2020-12-21 10:32

    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.

    0 讨论(0)
  • 2020-12-21 10:37

    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

    0 讨论(0)
  • 2020-12-21 10:45

    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.

    0 讨论(0)
提交回复
热议问题