To support move semantics, should function parameters be taken by unique_ptr, by value, or by rvalue?

后端 未结 4 958
忘了有多久
忘了有多久 2020-12-14 09:49

One of my function takes a vector as a parameter and stores it as a member variable. I am using const reference to a vector as described below.

class Test {
         


        
4条回答
  •  猫巷女王i
    2020-12-14 10:09

    The current advice on this is to take the vector by value and move it into the member variable:

    void fn(std::vector val)
    {
      m_val = std::move(val);
    }
    

    And I just checked, std::vector does supply a move-assignment operator. If the caller doesn't want to keep a copy, they can move it into the function at the call site: fn(std::move(vec));.

提交回复
热议问题