noncopyable
功能
允许程序轻松实现一个不可复制的类。
需包含头文件
#include<boost/noncopyable.hpp> 或
#include<boost/utility.hpp>
原理
在c++定义一个类时,如果不明确定义复制构造函数和复制赋值操作符,编译器会为我们自动生成这两个函数。
例如
class empty_class{ } ;
实际上类似于
class empty_class
{
public:
empty_class(const empty_class &){...}
empty_class & operator=(const empty_class &){...}
};
但有时候我们不要类的复制语义,希望禁止复制类的实现。比较常见的做法就是私有化复制构造函数和赋值操作符,
手写代码也很简单,如:
class do_not_copy
{
private:
do_not_copy(const do_not_copy &);
void operator=(const do_not_copy &);
};
但如果程序中有大量这样的类,重复写代码也是很麻烦的,解决方法也不够优雅。
noncopyable为实现不可复制的类提供了简单清晰的解决方案:从 boost::noncopyable 派生即可。
这里使用默认的私有继承是允许的,显示的写出private或public修饰词也可以,效果相同。我们定义的子类会自动私
有化父类noncopyable的复制构造函数,从而禁止用户从外部访问复制构造函数和复制赋值函数。
用法
以上例子也改写为:
class do_not_copy :boost::noncopyable
{...};
举例
#include<iostream>
#include<boost/utility.hpp>
#include<boost/noncopyable.hpp>
using namespace std;
using namespace boost;
class student:boost::noncopyable
{
public:
student(int _id):id(_id){};
int print(){return id;}
private:
int id;
};
int main()
{
student st(100);
cout<<st.print()<<endl;
student scopy(st); //报错
cout<<scopy.print()<<endl;
return 0;
}
若没有继承noncopyable
输出:
100
100
若继承,如上述代码,在注释那句开始报错。