Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is repeatedly calling move with rvalue references necessary?

Tags:

c++

c++11

move

struct Bar
{    
   Bar(std::string&& val)
    : m_Val(std::move(val)) {} // A

  Bar& operator=(Bar&& _other) { m_Val = std::move(_other.m_Val); }
  std::string m_Val;
}

struct Foo
{
  void Func1(Bar&& param)
  {
     Func2(std::move(param)) // B
  }

  void Func2(Bar&& param)
  {
     m_Bar = std::move(param); // C
  }

  Bar m_Bar;
};

void main()
{
   Foo f;
   std::string s = "some str";
   Bar b(std::move(s));
   f.Func1(std::move(b));
}

Give that you're calling move in main() to invoke the rvalue reference methods, is it necessary in lines A & B & C to repeat an additional call to move()? You already have the rvalue reference, so is it doing anything different in those lines with vs without?

I understand in Bar's operator= it's necessary because you're technically moving the m_Val rather than _other itself correct?

Note: Originally, I was incorrectly calling rvalue references as rvalue parameters. My apologies. I've corrected that to make the question easier to find and make clearer.

like image 394
user99999991 Avatar asked Feb 28 '19 15:02

user99999991


People also ask

When should we use std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

What is the point of rvalue reference?

Rvalue references enable you to write one version of a function that accepts arbitrary arguments. Then that function can forward them to another function as if the other function had been called directly.

How do rvalue references work?

An rvalue reference is formed by placing an && after some type. An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.

What is R Value reference in C ++ 11?

“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variable.


1 Answers

Give that you're calling move in main() to invoke the rvalue parameter methods, is it necessary in lines A & B & C to repeat an additional call to move()?

Yes. What you call an rvalue parameter is actually an rvalue reference. Just like a lvalue reference, it is an lvalue in the scope that it is being used. That means you need to use move to cast it back into an rvalue so that it gets moved, instead of copied. Remember, if the object has a name, it is an lvalue.

like image 195
NathanOliver Avatar answered Oct 06 '22 00:10

NathanOliver