Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an assignment from an rvalue reference type not invoke the move assignment operator? [duplicate]

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?

like image 921
Florian Avatar asked Sep 06 '25 03:09

Florian


1 Answers

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);
like image 90
NathanOliver Avatar answered Sep 09 '25 00:09

NathanOliver