mercredi 1 mars 2017

Why does the insertion of user defined destructor require an user defined copy constructor

The following code compiles:

#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class container
{
public:
    container(){}
    ~container(){}
};

class Ship
{
public:
    Ship(){}
    //Ship(const Ship & other){cout<<"COPY"<<endl;}
    //~Ship(){}

    std::unique_ptr<container> up;
};

Ship buildShip()
{
    Ship tmp;
    return tmp;
}

int main(int argc, char *argv[])
{
    return 0;
}

But if we out comment the user defined destructor ~Ship(){}, the code will only compile if we also out comment the user defined copy constructor Ship(const Ship & other){cout<<"COPY"<<endl;}

Why does the insertion of user defined destructor require an user defined copy constructor and why do we need a copy constructor in the above example at all?

I would expect that there is no copy constructor needed in the example above, as unique_ptr can not even be copied.

Aucun commentaire:

Enregistrer un commentaire