1 #include <QCoreApplication>
2 #include <thread>
3 #include <iostream>
4
5
6 /*
7 * 话题: 删除函数。
8 * 函数使用 =delete 说明符。 全局函数,类成员函数均可使用。
9 *
10 * 1. 通过添加 =delete 将一个函数声明为删除函数。 调用被删除的函数会引发编译错误。
11 *
12 * 实例情景:
13 * 1. 杜绝对象被拷贝和赋值。 例如:std::mutex, std::unique_lock等
14 * 将拷贝构造函数和赋值运算符声明为删除函数。 这个时候,务必显示的声明移动构造函数和移动赋值运算符。我们的类只移动。
15 *
16 * 2. =delete说明符与函数重载相结合使用, 可以删除特定的重载。
17 * 比如,void func(short); void func(int); 当我们以short作为参数, 为避免扩展为int, 可以将 void func(int) = delete 声明为删除函数。
18 *
19 */
20
21 //! [0] 实例情景:-1
22 class thread_guard{
23 public:
24 thread_guard(std::thread & t):_t(t){}
25 ~thread_guard(){
26 if (_t.joinable())
27 _t.join();
28 }
29
30 thread_guard(thread_guard & other) = delete;
31 thread_guard(thread_guard &&other):_t(std::move(other._t)){}
32
33 thread_guard & operator=(thread_guard & other) = delete;
34 thread_guard & operator=(thread_guard && other){
35 _t = std::move(other._t);
36 return *this;
37 }
38
39 private:
40 std::thread & _t;
41 };
42
43 void hello(){
44 std::cout<<"hello word "<<std::endl;
45 }
46 //! [0]
47
48
49
50 //! [1] 实例情景:-2
51 void func(short a){
52 std::cout<<a<<" sizeof is "<<sizeof(a)<<std::endl;
53 }
54 #if 0
55 void func(int a){
56 std::cout<<a<<" sizeof is "<<sizeof(a)<<std::endl;
57 }
58 #else
59 void func(int a) = delete;
60 #endif
61
62 //! [1]
63 int main(int argc, char *argv[])
64 {
65 QCoreApplication a(argc, argv);
66
67 //! [0]
68 {
69 std::thread t(hello);
70 thread_guard _guard(t);
71 //thread_guard _guardOther(_guard); //error info: thread_guard::thread_guard(thread_guard &) 尝试引用已删除的函数
72 thread_guard _guardOther(std::move(_guard)); //想要移动左置, 需显示使用 std::move 或者 static_cast<T&&>()
73 }
74 //! [0]
75
76 std::cout<<std::endl;
77 //! [1]
78 int _v = 10;
79 //func(_v); //error: void func(int) 尝试引用已删除的函数
80 //因 void func(int) 声明为删除函数,因此任何向 func传递整形的调用都会产生一个编译错误。
81
82 func(short(_v)); //调用时可显示的转换
83 //! [1]
84
85 return a.exec();
86 }