boost::noncopyable 的作用

boost::noncopyable 的作用

boost::noncopyable 是用于针对 C++ 编译器的。具体看下面的代码:

#include <iostream>
using namespace std;

class car{
public:
	car(int price) : _price(price){
	}
	int getPrice() const {return _price;}
private:
	int _price;
}; 

int main(){
	car a(10);
	car b(a);
	car c(0);
	cout << c.getPrice() << endl;
	c = b;
	cout << c.getPrice() << endl;
	return 0;
}

代码运行结果为:

0
10

我们在 car 类中并没有显示地声明和定义拷贝构造函数拷贝赋值操作符,但是在 main 中却调用了这两个函数。奇怪的是编译竟然通过了,由此而知编译器默认行为就是帮你添加拷贝构造函数拷贝赋值操作符,果然,通过程序最后运行的结果显示了我们的猜想。

但是我们有时候并不需要拷贝构造函数拷贝赋值操作符呀,那该怎么办?

方法一就是私有化拷贝构造函数拷贝赋值操作符,这样用户就无法调用类的私有成员函数了,如下所示:

class car{
public:
	car(int price) : _price(price){
	}
	int getPrice() const {return _price;}
private:
	car(const car& a){
		_price = a.getPrice();
	}
	car& operator=(const car& a){
		_price = a.getPrice();
	}
	int _price;
}; 

这样编译就通不过了。

当然这样写起来很麻烦,可以直接让类继承自 boost::noncopyable ,这样编译器就不会默认添加拷贝构造函数拷贝赋值操作符了!

原文地址:https://www.cnblogs.com/Codroc/p/13582717.html