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.
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.
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.
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.
“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.
Give that you're calling
move
inmain()
to invoke the rvalue parameter methods, is it necessary in lines A & B & C to repeat an additional call tomove()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With