jeudi 2 juin 2016

Can a derived class be made uncopyable by deleting the copy constructor/operators in the base class?

Pre C++11, I asked whether this was possible using the private/not-implemented trick (see here). Apparently, this was not possible.

I wonder whether the new = delete syntax has changed the state of affairs, as forcing derived classes to be uncopyable would still be a useful feature.

The updated code snippet could look something along these lines:

class Base 
{
public:
    Base() {}
    virtual ~Base() {}
    Base(const Base&) = delete;
    Base& operator=(const Base&) = delete;

    virtual void interfaceFunction() = 0;
    // etc.

    // no data members
};

class Data { /* ... */ };
class Derived : public Base  // is this class uncopyable ?
{
    Derived() : managedData(new Data()) { }
    ~Derived() ( delete managedData; }

    virtual void interfaceFunction() override { /* ... */ }

    Data* managedData; 
};

Aucun commentaire:

Enregistrer un commentaire