mercredi 3 février 2021

What is the best practice if I want to forward a variable to be moved in C++?

#include <utility>
class SomeObject {
// ...Object Definition
};

void B(SomeObject& so)
{
    SomeObject movedTo = std::move(so);
}

void A(SomeObject& so)
{
    B(so);
}

int main()
{
    SomeObject movedFrom;
    A(movedFrom);

    return 0;
}

For example, now I have two functions A and B. Function A may first do something, then pass the argument so to function B. In function B, I will move the passed argument so. What confused me a lot is that there is another way to do this:

#include <utility>
class SomeObject {
// ...Object Definition
};

void B(SomeObject&& so)
{
    SomeObject movedTo = std::move(so);
}

void A(SomeObject&& so)
{
    B(std::move(so));
}

int main()
{
    SomeObject movedFrom;
    A(std::move(movedFrom));

    return 0;
}

In the second version, the parameter of function A and B are rvalue references. Both of these codes compiles, and both of them work well. So, which one is the better practice of doing such kind of thing?

Aucun commentaire:

Enregistrer un commentaire