日积月累: Uncopyable && Uninheritable in C++
如何在C++中阻止复制和继承呢,我做了个整理。
Uncopyable
有些类需要禁止被复制或者赋值,这需要显示的禁掉它们的拷贝构造和赋值函数。
摘自《Effective C++》Item 6: Explicitly disallow the use of compiler-generated functions you do not want
class Uncopyable
{
protected: // allow construction
Uncopyable() {} // and destruction of
~Uncopyable() {} // derived objects...
private:
Uncopyable(const Uncopyable&); // ...but prevent copying
Uncopyable& operator=(const Uncopyable&);
};
class UncopyableExample: private Uncopyable
{
// THIS CLASS IS UNCOPYABLE
};
Uninheritable
Java提供了final关键字用来阻止被继承,而在C++中没有这个关键字,但阻止继承的类在C++中是同样可能的。
摘自:http://www.csse.monash.edu.au/~damian/Idioms/Topics/04.SB.NoInherit/html/text.html
template <class OnlyFriend>
class Uninheritable
{
friend class OnlyFriend;
Uninheritable(void) {}
};
class NotABase : virtual public Uninheritable< NotABase >
{
// WHATEVER
};
class NotADerived: public NotABase
{
// THIS CLASS GENERATES A COMPILER ERROR
NotADerived(){}
};