boost实用工具:创建一个禁止复制的类 noncopyable

  boost的noncopyable允许创建一个禁止复制的类,使用很简单,但很好用!

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
 
/* 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();
    
return 0;
}
原文地址:https://www.cnblogs.com/MakeView660/p/7025782.html