vendredi 10 janvier 2020

How move semantics works here?

I have the following example and I am not sure I fully understand the move semantic logic:

#include <iostream>
#include <string>
#include <memory>

class Player
{
public:
    Player(std::string name)
        : m_name(std::move(name)) {}

private:
    std::string m_name;
};

int main()
{
    std::string s = "Zidane";
    std::cout << s << std::endl;

    Player player1(s); // not moved
    std::cout << s << std::endl; // s = "Zidane"

    Player player2(std::move(s)); // moved -> s is empty now
    std::cout << s << std::endl;

    return 0;
}

My explanation is that in the first case (Player1), name which is an lvalue of type std::string is actually copied before the ctor of m_name is called, then, the std::move acts on the copy, so at the end the copy is empty and its content has been moved to m_name using the move ctor. That's why the original argument s remains untouched. Is it correct?

In the second case, it's not clear: std::move converts the lvalue parameter into a reference lvalue and from there what happen In this case, the argument s is empty after the call.

Aucun commentaire:

Enregistrer un commentaire