/* boost_noncopyable.cpp 创建一个禁止复制的类 noncopyable允许程序轻松实现一个禁止复制的类; */
#include <iostream> #include <boost/noncopyable.hpp> // 或#include <boost/utility.hpp>
using namespace std; using namespace boost;
//在C++中定义一个类的时候,如果不明确定义拷贝构造函数和拷贝复制操作符,编译器会为我们自动生成 //但有时候我们不需要类的复制语义,希望禁止复制类的实例 //这是一个很经典的C++惯用语法,只要私有化拷贝构造函数和拷贝赋值操作函数即可 //如果程序中有大量这样的类,重复写这样的代码是相当乏味的,而且代码出现的次数越多越容易增加手写出错的几率 class empty_class { public: empty_class() {} ~empty_class() {}
//编译器默认添加拷贝构造函数和拷贝赋值函数 empty_class(const empty_class & ) {} empty_class &operator=(const empty_class &) {} protected: private: };
class noncopy_class { public: noncopy_class() {} ~noncopy_class() {} protected: private: //私有化拷贝构造函数和拷贝赋值函数,禁止复制类 noncopy_class(const noncopy_class & ) {} noncopy_class &operator=(const noncopy_class &) {} };
//针对以上情况,boost中的noncopyable为实现不可拷贝类提供了简单清晰的解决方案 //从boost::noncopyable派生即可 /* class noncopyable { protected: #if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS) BOOST_CONSTEXPR noncopyable() = default; ~noncopyable() = default; #else noncopyable() {} ~noncopyable() {} #endif #if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) noncopyable( const noncopyable& ) = delete; noncopyable& operator=( const noncopyable& ) = delete; #else private: // emphasize the following members are private noncopyable( const noncopyable& ); noncopyable& operator=( const noncopyable& ); #endif }; }
typedef noncopyable_::noncopyable noncopyable; */ class do_not_copy_class : noncopyable { public: protected: private: };
int main(void) { empty_class em_c1; empty_class em_c2(em_c1); empty_class em_c3 = em_c1;
noncopy_class noc_c1; //error C2248: ‘noncopy_class::noncopy_class’ : cannot access private member declared in class ‘noncopy_class’ //noncopy_class noc_c2(noc_c1) ; //noncopy_class noc_c3 = noc_c1;
do_not_copy_class d1; //error C2248: ‘boost::noncopyable_::noncopyable::noncopyable’ : cannot access private member declared in class ‘boost::noncopyable_::noncopyable’ //do_not_copy_class d2(d1); //do_not_copy_class d3 = d1;
//只要有可能就使用boost::noncopyable,它明确无误地表达了类设计者的意图; //对用户更加友好,而且与其它的boost库配合的也好 cin.get(); ; } |