ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

=delete 删除函数

2021-09-20 12:02:08  阅读:185  来源: 互联网

标签:std 函数 thread guard other 删除 delete


 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 }

 

标签:std,函数,thread,guard,other,删除,delete
来源: https://www.cnblogs.com/azbane/p/15314024.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有