mardi 11 février 2020

Interaction between copy-and-swap idiom and move operations

I'm trying to make a program that implements the interaction between "copy and swap" idiom and and move control operations so I wrote this code:

class PInt
{
public:
    PInt(int = 0);
    PInt(const PInt&);
    PInt(PInt&&) noexcept;
    PInt& operator=(PInt);
    ~PInt();

    int* getPtr()const;

private:
    int* ptr;
    friend void swap(PInt&, PInt&);
};

PInt::PInt(int x) : 
    ptr(new int(x))
{
    std::cout << "ctor\n";
}

PInt::PInt(const PInt& rhs) :
    ptr(new int(rhs.ptr ? *rhs.ptr : 0))
{
    std::cout << "copy-ctor\n";
}

PInt::PInt(PInt&& rhs) noexcept :
    ptr(rhs.ptr)
{
    std::cout << "move-ctor\n";
    rhs.ptr = nullptr; // putting rhs in a valid state
}


PInt& PInt::operator=(PInt rhs)
{
    std::cout << "copy-assignment operator\n";
    swap(*this, rhs);
    return *this;
}

PInt::~PInt()
{
    std::cout << "dtor\n";
    delete ptr;
}

void swap(PInt& lhs, PInt& rhs)
{
    std::cout << "swap(PInt&, PInt&\n";
    using std::swap;
    swap(lhs.ptr, rhs.ptr);
}

PInt gen_PInt(int x)
{
    return {x};
}

int main()
{
    PInt pi1(1), pi2(2);
    //pi1 = pi2; // 1
    //pi1 = PInt{}; // 2
    //pi1 = std::move(pi2); // 3
    pi1 = std::move(PInt{}); // 4


}
  • Everything is OK for me so I think in 1 the copy-ctor is invoked by copy-asignment operator to initialize its parameter (it takes by value) then uses swap. in "2" I am assigning from an r-value thus I think the compiler applies some "Copy-elision" optimization; creating directly an object in the copy-assignment operator.

  • What I am not sure of is from 3 and 4. so here is the result of 3 and 4:

    un-commenting line 3:

    ctor
    ctor
    move - ctor
    copy - assignment operator
    swap(PInt&, PInt &
    dtor
    dtor
    dtor
    

Un-commenting line 4:

    ctor
    ctor
    ctor
    move - ctor
    copy - assignment operator
    swap(PInt&, PInt &
    dtor
    dtor
    dtor
    dtor
  • Why 3 and 4 use std::move but for gets n extra constructor called?

Aucun commentaire:

Enregistrer un commentaire