noncopyable为实现不可拷贝的类提供了简单清晰的解决方案。使用的boost库
h文件:
#ifndef BASE_H
#define BASE_H
#include <cstdlib>
#include <iostream>
#include <boost/utility.hpp>
using namespace std;
class Base : private boost::noncopyable
{
public:
Base(int num);
int getNumber() const;
private:
Base(Base const&);
Base& operator =(Base const&);
private:
int number;
};
#endif // BASE_H
cpp文件
#include "base.h"
Base::Base(int num)
{
number = num;
}
int Base::getNumber() const
{
return number;
}
main.cpp文件
#include <iostream>
#include "base.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
Base b(5);
cout<<b.getNumber()<<endl;
Base b1(b);
Base b2;
b2 = b;
return 0;
}
编译会报错:
即可实现 类的不可拷贝。
noncopyable的源码:
class noncopyable
{
protected:
noncopyable() = default;
~noncopyable() = default;
public:
noncopyable( const noncopyable& ) = delete;
noncopyable& operator=( const noncopyable& ) = delete;
};