Disabling GCC Warnings When Using the "Uncopyable" Class
I have several classes that I don't want to copy, some of these classes have pointer data members. To make these classes heavy, I privately inherit the following template template:
template <class T>
class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
T & operator=(const T&);
};
Which I used like this:
class Entity : private Uncopyable<Entity> { }
This works great, however, when I compile with -WeffC ++ I still get the following warning:
class Entity has pointer data members
but does not override Entity(const Entity&)
or operator=(const Entity&)
Why is it still giving me this warning?
source to share
C ++ says
Since a copy assignment operator is implicitly declared for a class, unless it is declared by the user, the base class assignment operator is always hidden by the derived class copy assignment operator (13.5.3). A use-declaration (7.3.3) that brings from the base class an assignment operator with a parameter type that can be of the copy assignment type, the operator of the derived class is not considered an explicit declaration of the copy-assignment operator and does not suppress the implicit declaration of the assignment operator of the derived class; a statement introduced by a declaration-declaration is hidden by an implicitly declared copy assignment statement in the derived class.
The error in your code is that your base class declares operator=
to accept a type reference of a derived class. This will not prevent the implicit public declaration of the operator = for the base. This way your derived class and your base class can still be assigned. Try changing the noncopyable class to non-template, which should suffice:
class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
Uncopyable & operator=(const Uncopyable&);
};
Another thing I just figured out in this code: don't make the destructor of the virtual machine Uncopyable. The reason is that no one (other than the derived class itself) can call delete on a pointer to Uncopyable (because 1: the destructor is protected, 2: you get privately). So it's not an Uncopyable problem to make the derived class's destructor implicitly virtual. If the derived class should have a virtual destructor, insert a virtual one instead, and leave the Uncopyables destructor non-virtual.
source to share