Consider the following code:
#include <iostream>
#include <string>
struct my_struct {
void func(std::string&& str) {
str_ = str;
}
std::string str_;
};
int main() {
my_struct s;
std::string str("Hello");
s.func(std::move(str));
std::cout << str << std::endl;
std::cout << s.str_ << std::endl;
}
Why do I need an extra std::move
in my_struct::func
in order to invoke the move assignment operator of std::string
? What would the extra std::move
exactly do? I thought it would just cast the given type to its rvalue reference counterpart?
When you do str_ = str;
, str
is a named variable. That means inside your function str
is an lvalue, not an rvalue. This means copy assignment is used and not move assignment.
What you need to do is get str
back to an rvalue and you can do that with std::move
like
str_ = std::move(str);
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