jeudi 2 novembre 2023

How to (properly) move non-static data members?

Let’s say I have a class with a non-static data member that’s worthy to be moved, e.g. a std::vector. When I write a get accessor to it, using ref qualifiers, I can distinguish between lvalue and rvalue of the class object. In the lvalue case, I’ll copy the member, but in the rvalue case, I’d move it. For this, I have seen two syntaxes tagged A and B in the following snippet:

class C
{
    std::vector<int> m_values;
public:
    std::vector<int> values() const &;
    std::vector<int> values() &&
    {
        return std::move(m_values); // A
        return std::move(*this).m_values; // B
    }
};

I tested both and they both move the value. I get why one would use A, it’s plain obvious what’s intended. I find B weird, so why do people use it? What are the advantages?

The answers to the following questions contain no answer to my question:

Aucun commentaire:

Enregistrer un commentaire