C++ 说
因为如果用户未声明复制赋值运算符,则会为类隐式声明,因此基类复制赋值运算符始终被派生类的复制赋值运算符隐藏(13.5.3)。从基类引入赋值运算符的 using-declaration (7.3.3),其参数类型可能是派生类的复制赋值运算符的类型,不被视为复制赋值运算符的显式声明,并且不抑制派生类复制赋值运算符的隐式声明;由 using 声明引入的运算符被派生类中隐式声明的复制赋值运算符隐藏。
代码中的错误是您的基类声明operator=
接受派生类类型的引用。这不会阻止隐式公开声明 operator= 为基础。因此,您的派生类和基类仍然是可分配的。尝试将您的不可复制类更改为非模板,这应该足够了:
class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
Uncopyable & operator=(const Uncopyable&);
};
One more thing i have just figured in that code: Don't make the destructor of Uncopyable virtual. The reason is, no-one (apart from the derived class itself) can call delete on a pointer to Uncopyable (because 1: the destructor is protected, 2: you derive privately). So it's not the concern of Uncopyable to make the destructor of the derived class implicitly virtual. If the derived class needs to have a virtual destructor, put virtual in there instead, and leave Uncopyables' destructor non-virtual.