vendredi 21 août 2015

Ensuring that a member variable is moved, if the object is a rvalue

Please consider the following piece of code:

class A
{
public:
    A(/* params */) {
        // Fill m_data depending on params
    }

    std::vector<double> get_data() const noexcept {
        return m_data;
    }

private:
    std::vector<double> m_data;
};

std::vector<double> get_data() {
    return A{/* suitable params */}.get_data();
}

What I want is, that m_data is moved to the caller of the function get_data(), i.e. no copies should be made.

How can I be sure, that this is the case? Clearly, A{/* suitable params */} is a rvalue. Hence, it's member variable m_data is a rvalue in this context. So, is it enough to add another member function

std::vector<double> get_data() && noexcept {
    return std::move(m_data);
}

Aucun commentaire:

Enregistrer un commentaire