dimanche 15 novembre 2020

Is it feasible to optimize the assignment operator with swap

It is inefficient to use a single assignment operator to handle both copy and move assignments:Why is it not efficient to use a single assignment operator handling both copy and move assignment?

If the copy assignment operator and the move assignment operator are defined separately, and copy-and-swap are used in the copy assignment operator, and swap is used in the move assignment operator,Is this code more efficient than using copy-and-swap to define assignment operators ?

class A;
void swap(A & , A &);

class A
{
    friend void swap(A & , A &);
public:
    A() : a(nullptr) , b(nullptr) {}

    //copy construct
    A(const A &rhs) : a(new int (*rhs.a)) , b(new char (*rhs.b)){}

    //move construct
    A(A &&rhs) noexcept : a(rhs.a) , b(rhs.b)
    {
        rhs.a = nullptr;
        rhs.b = nullptr;
    }

    //copy operator=
    A& operator= (const A &rhs){
        A temp = rhs;
        swap(*this , temp);
        return *this;
    }

    //move operator=
    A& operator= (A &&rhs) noexcept
    {
        swap(*this , rhs);
        return *this;
    }
    
    ~A()
    {
        delete a;
        delete b;
    }
private:
    int *a;
    char *b;
};

void swap(A &lhs , A &rhs)
{
    using std::swap;
    swap(lhs.a , rhs.a);
    swap(lhs.b , rhs.b);
}

and this is use copy-and-swap to define a single assignment operator:

A& operator=(A rhs)
{
    using std::swap;
    swap(*this , rhs);
    return *this;
}

Aucun commentaire:

Enregistrer un commentaire