如何在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(){}
};

学习了,呵呵
啊。。专家。。
呵呵,我只是转载做份收藏而已~
Pingback: Music Sets Me Free » Blog Archive » 让管理lua_State的类指针安全
Pingback: 让管理lua_State的类指针安全 | Nutty Coder
Uninheritable的实现有问题,大部分编译器都无法编译通过。
因为C++的标准中禁止将模板参数作为friend
谢谢提醒