mercredi 26 août 2015

Should C++11 Move and Copy Assignment Operators return const?

Should C++11 Move and Copy Assignment Operators return const?

Example code:

const my_class& operator=(const my_class& other)
{
    // Copy the data
    my_class tmp(other);
    *this = std::move(tmp);

    return *this;
}


const my_class& operator=(my_class&& other)
{
    // Steal the data
    std::swap(my_data_length, other.my_data_length);
    std::swap(my_data, other.my_data);

    return *this;
}

For clarity:

class my_class
{

    protected:

    double *my_data;
    uint64_t my_data_length;
}

Notice the const on the return type. I usually put this without thinking, but is it really necessary? What does returning const prevent you from doing? (An example would be helpful here.)

Aucun commentaire:

Enregistrer un commentaire