You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Tool_tutorial.md 31 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. # 工具使用合集
  2. [toc]
  3. ## Visual Studio使用说明
  4. 比赛**只保证!!!支持**VS2022最新版本,选手使用其他版本后果自负(实际上应该不能编译)。
  5. ### 生成模式的设置
  6. 菜单栏下方一行
  7. ![image-20230416010705076](../resource/image-20230416010705076.png)
  8. 可以更改生成模式为`Debug`或`Release`
  9. ### 命令行参数的设置
  10. 左上方菜单栏 `调试->调试属性`
  11. ![image-20230416010816392](../resource/image-20230416010816392.png)
  12. 在命令参数一栏中加入命令行参数进行调试
  13. ### cmd脚本的参数修改
  14. 右键点击`.cmd`或`.bat`文件之后,选择编辑就可以开始修改文件。通过在一行的开头加上`::`,可以注释掉该行。
  15. ## C++接口必看
  16. **在此鸣谢\xfgg/\xfgg/\xfgg/,看到这里的选手可以到选手群膜一膜!!! **
  17. 除非特殊指明,以下代码均在 MSVC 19.28.29913 /std:c++17 与 g++ 10.2 for linux -std=c++17 两个平台下通过。
  18. 由于我们的比赛最终会运行在Linux平台上,因此程设课上学到的一些只适用于Windows的C++操作很可能并不能正确执行。此外,代码中使用了大量Modern C++中的新特性,可能会使选手在编程过程中遇到较大困难。因此,此处介绍一些比赛中使用C++接口必须了解的知识。
  19. ### 计时相关
  20. 编写代码过程中,我们可能需要获取系统时间等一系列操作,C++ 标准库提供了这样的行为。尤其注意**不要**使用 Windows 平台上的 `GetTickCount` 或者 `GetTickCount64` !!! 应当使用 `std::chrono`
  21. 头文件:`#include <chrono>`
  22. 可以用于获取时间戳,从而用于计时、例如计算某个操作花费的时间,或者协调队友间的合作。
  23. ```c++
  24. #include <iostream>
  25. #include <chrono>
  26. int main()
  27. {
  28. auto sec = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  29. auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  30. std::cout << "从 1970 年元旦到现在的:秒数" << sec << ";毫秒数:" << msec << std::endl;
  31. return 0;
  32. }
  33. ```
  34. ### 线程睡眠
  35. 由于移动过程中会阻塞人物角色,因此玩家可能要在移动后让线程休眠一段时间,直到移动结束。C++ 标准库中使线程休眠需要包含头文件:`#include <thread>`。示例用法:
  36. ```cpp
  37. std::this_thread::sleep_for(std::chrono::milliseconds(20)); // 休眠 20 毫秒
  38. std::this_thread::sleep_for(std::chrono::seconds(2)); // 休眠 2 秒
  39. // 下面这个也能休眠 200 毫秒
  40. std::this_thread::sleep_until(std::chrono::system_clock::now() += std::chrono::milliseconds(200));
  41. ```
  42. 休眠过程中,线程将被阻塞,而不继续进行,直到休眠时间结束方继续向下执行。
  43. ### 异步接口的使用
  44. 本届比赛中,我们可能会看到类似 `std::future<bool>` 这样类型的接口返回值,这实际上是一个异步接口。在调用同步接口后,在接口内的函数未执行完之前,线程通常会阻塞住;但是异步接口的调用通常不会阻塞当前线程,而是会另外开启一个线程进行操作,当前线程则继续向下执行。当调用 `get()` 方法时,将返回异步接口的值,若此时异步接口内的函数依然未执行完,则会阻塞当前线程。
  45. 如果不需要返回值或没有返回值,但是希望接口内的函数执行完之后再进行下一步,即将接口当做常规的同步接口来调用,也可以调用 `wait()` 方法。
  46. ```c++
  47. #include <iostream>
  48. #include <thread>
  49. #include <future>
  50. #include <chrono>
  51. int f_sync()
  52. {
  53. std::this_thread::sleep_for(std::chrono::seconds(1));
  54. return 8;
  55. }
  56. std::future<int> f_async()
  57. {
  58. return std::async(std::launch::async, []()
  59. { std::this_thread::sleep_for(std::chrono::seconds(1));
  60. return 8; });
  61. }
  62. int main()
  63. {
  64. auto start = std::chrono::system_clock::now();
  65. std::cout << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - start).count() << std::endl;
  66. auto x = f_async();
  67. std::cout << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - start).count() << std::endl;
  68. std::cout << x.get() << std::endl;
  69. std::cout << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - start).count() << std::endl;
  70. auto y = f_sync();
  71. std::cout << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - start).count() << std::endl;
  72. std::cout << y << std::endl;
  73. std::cout << std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(std::chrono::system_clock::now() - start).count() << std::endl;
  74. }
  75. ```
  76. ### `auto`类型推导
  77. C++11开始支持使用 `auto` 自动推导变量类型,废除了原有的作为 storage-class-specifier 的作用:
  78. ```c++
  79. int i = 4;
  80. auto x = i; // auto 被推导为 int,x 是 int 类型
  81. auto& y = i; // auto 仍被推导为 int,y 是 int& 类型
  82. auto&& z = i; // auto 被推导为 int&,z 是 int&&&,被折叠为 int&,即 z 与 y 同类型
  83. auto&& w = 4; // auto 被推导为 int,w 是 int&& 类型
  84. ```
  85. ### STL相关
  86. #### std::vector
  87. 头文件:`#include <vector>`,类似于可变长的数组,支持下标运算符 `[]` 访问其元素,此时与 C 风格数组用法相似。支持 `size` 成员函数获取其中的元素数量。
  88. 创建一个 `int` 型的 `vector` 对象:
  89. ```cpp
  90. std::vector<int> v { 9, 1, 2, 3, 4 }; // 初始化 vector 有五个元素,v[0] = 9, ...
  91. v.emplace_back(10); // 向 v 尾部添加一个元素,该元素饿构造函数的参数为 10(对于 int,只有一个语法意义上的构造函数,无真正的构造函数),即现在 v 有六个元素,v[5] 的值是10
  92. v.pop_back(); // 把最后一个元素删除,现在 v 还是 { 9, 1, 2, 3, 4 }
  93. ```
  94. 遍历其中所有元素的方式:
  95. ```cpp
  96. // std::vector<int> v;
  97. for (int i = 0; i < (int)v.size(); ++i)
  98. {
  99. /*可以通过 v[i] 对其进行访问*/
  100. }
  101. for (auto itr = v.begin(); itr != v.end(); ++itr)
  102. {
  103. /*
  104. * itr 作为迭代器,可以通过其访问 vector 中的元素。其用法与指针几乎完全相同。
  105. * 可以通过 *itr 得到元素;以及 itr-> 的用法也是支持的
  106. * 实际上它内部就是封装了指向 vector 中元素的指针
  107. * 此外还有 v.cbegin()、v.rbegin()、v.crbegin() 等
  108. * v.begin()、v.end() 也可写为 begin(v)、end(v)
  109. */
  110. }
  111. for (auto&& elem : v)
  112. {
  113. /*
  114. * elem 即是 v 中每个元素的引用,也可写成 auto& elem : v
  115. * 它完全等价于:
  116. * {
  117. * auto&& __range = v;
  118. * auto&& __begin = begin(v);
  119. * auto&& __end = end(v);
  120. * for (; __begin != __end; ++__begin)
  121. * {
  122. * auto&& elem = *__begin;
  123. * // Some code
  124. * }
  125. * }
  126. */
  127. }
  128. ```
  129. 例如:
  130. ```cpp
  131. for (auto elem&& : v) { std::cout << elem << ' '; }
  132. std::cout << std::endl;
  133. ```
  134. 作为 STL 的容器之一,其具有容器的通用接口。但是由于这比较复杂,在此难以一一展开。有兴趣的同学可以在下方提供的链接里进行查阅。
  135. **注:请千万不要试图使用 `std::vector<bool>`,若需使用,请用 `std::vector<char>` 代替!**
  136. 更多用法参见(点击进入):[cppreference_vector](https://zh.cppreference.com/w/cpp/container/vector)
  137. #### std::array
  138. 头文件:`#include <array>`,C 风格数组的类封装版本。
  139. 用法与 C 风格的数组是基本相似的,例如:
  140. ```cpp
  141. std::array<double, 5> arr { 9.0, 8.0, 7.0, 6.0, 5.0 };
  142. std::cout << arr[2] << std::endl; // 输出 7.0
  143. ```
  144. 同时也支持各种容器操作:
  145. ```cpp
  146. double sum = 0.0;
  147. for (auto itr = begin(arr); itr != end(arr); ++itr)
  148. {
  149. sum += *itr;
  150. }
  151. // sum 结果是 35
  152. ```
  153. 更多用法参见(点击进入):[cppreference_array](https://zh.cppreference.com/w/cpp/container/array)。
  154. ## Python接口必看
  155. 比赛**只保证!!**支持Python3.9,不保证支持其他版本
  156. 比赛中的Python接口大多使用异步接口,即返回一个类似于 `Future[bool]` 的值。为了获取实际的值,需要调用 `result()` 方法。
  157. ```python
  158. from concurrent.futures import Future, ThreadPoolExecutor
  159. import time
  160. class Cls:
  161. def __init__(self):
  162. self.__pool: ThreadPoolExecutor = ThreadPoolExecutor(10)
  163. def Test(self, a: int, b: int) -> Future[int]:
  164. def test():
  165. time.sleep(0.5)
  166. return a + b
  167. return self.__pool.submit(test)
  168. if __name__ == '__main__':
  169. f1 = Cls().Test(1, 2)
  170. print(time.time())
  171. print(f1.result())
  172. print(time.time())
  173. ```
  174. ## C++相关小知识
  175. ### lambda表达式
  176. #### lambda表达式概述
  177. lambda 表达式是 C++ 发展史上的一个重大事件,也是 C++ 支持函数式编程的重要一环。可以说,lambda 表达式不仅给 C++ 程序员带来了极大的便利,也开创了 C++ 的一个崭新的编程范式。但是同时 lambda 表达式也带来了诸多的语法难题,使用容易,但精通极难。
  178. lambda 表达式确实是一个非常有用的语法特性。至少个人在学了 lambda 表达式之后,编写 C++ 代码就再也没有离开过。因为,它真的是非常的方便与易用。
  179. lambda 表达式首先可以看做是一个临时使用的函数。它的一般格式如下:
  180. ```c++
  181. [捕获列表] + lambda 声明(可选) + 复合语句
  182. lambda 声明指的是:
  183. (参数列表) + 一堆修饰符(可选)
  184. ```
  185. 下面是一个简单的例子:
  186. ```c++
  187. #include <iostream>
  188. using namespace std;
  189. int main(void)
  190. {
  191. auto GetOne = []{ return 1; }; // GetOne 是一个 lambda 表达式
  192. cout << GetOne() << endl; // 使用起来就像一个函数,输出 1
  193. return 0;
  194. }
  195. ```
  196. 它还可以有参数:
  197. ```c++
  198. #include <iostream>
  199. using namespace std;
  200. int main(void)
  201. {
  202. auto GetSum = [](int x, int y){ return x + y; };
  203. cout << GetSum(2, 3) << endl; // 5
  204. return 0;
  205. }
  206. ```
  207. 或者临时调用:
  208. ```c++
  209. #include <iostream>
  210. using namespace std;
  211. int main(void)
  212. {
  213. cout << [](int x, int y){ return x + y; }(2, 3) << endl; // 5
  214. return 0;
  215. }
  216. ```
  217. #### lambda 表达式的捕获
  218. ##### 捕获的概念
  219. lambda 表达式是不能够直接使用函数内的局部变量的(之后你将会看到这是为什么)。如果需要使用函数内的局部变量,需要手动进行捕获。捕获的方式有两种:按值捕获与按引用捕获。按值捕获,只会获得该值,而按引用捕获,则会获得函数内局部变量的引用。声明要捕获的变量就在 lambda 表达式的 `[]` 内:
  220. + `[]`:不捕获任何局部变量
  221. + `[x]`:按值捕获变量 `x`
  222. + `[&y]`:按引用捕获变量 `y`
  223. + `[=]`:按值捕获全部局部变量
  224. + `[&]`:按引用捕获全部局部变量
  225. + `[&, x]`:除了 `x` 按值捕获之外,其他变量均按引用捕获
  226. + `[=, &y]`:什么意思不用我都说了吧
  227. + `[r = x]`:声明一个变量 `r` ,捕获 `x` 的值
  228. + `[&r = y]`:声明一个引用 `r`,捕获 `y` 的引用
  229. + `[x, y, &z, w = p, &r = q]`:作为练习
  230. + `[&, x, y, p = z]`:这个也作为练习
  231. 这样我们就可以写出下面的代码了:
  232. ```cpp
  233. #include <iostream>
  234. using namespace std;
  235. int main(void)
  236. {
  237. int x, y, z;
  238. cin >> x >> y;
  239. [x, y, &z](){ z = x + y; }();
  240. cout << z << endl; // z = x + y
  241. return 0;
  242. }
  243. ```
  244. ##### 捕获 `this` 与 `*this`
  245. 当 lambda 表达式位于类的成员函数内时,该如何使用该类的成员变量呢?我们知道,在类的成员函数体内使用成员变量,都是通过 `this` 指针访问的,此处 `this` 作为成员函数的一个参数,因此只需要捕获 `this` 指针,就可以在 lambda 体内访问其成员变量了!
  246. 捕获时,我们可以选择捕获 `[this]`,也可以捕获 `[*this]`。区别是,前者捕获的是 `this` 指针本身,而后者是按值捕获 `this` 指针所指向的对象,也就是以 `*this` 为参数复制构造了一个新的对象。看下面的代码:
  247. ```c++
  248. #include <iostream>
  249. using namespace std;
  250. struct Foo
  251. {
  252. int m_bar;
  253. void Func()
  254. {
  255. [this]()
  256. {
  257. cout << ++m_bar << endl;
  258. }();
  259. }
  260. };
  261. int main()
  262. {
  263. Foo foo;
  264. foo.m_bar = 999;
  265. foo.Func(); // 输出 1000
  266. }
  267. ```
  268. ##### 附注
  269. 需要注意的是,lambda 表达式的捕获发生在 **lambda 表达式定义处**,而不是 lambda 表达式调用处,比如:
  270. ```c++
  271. int a = 4;
  272. auto f = [a]() { cout << a << endl; }; // 此时捕获 a,值是 4
  273. a = 9;
  274. f(); // 输出 4,而非 9
  275. ```
  276. > **C++ 真奇妙:不需要捕获的情况**
  277. >
  278. > 看这特殊的引用块就知道,本段内容仅作介绍,感觉较难者请跳过本块。
  279. >
  280. > 有时,即使是局部变量,不需要捕获也可以编译通过。这是 C++ 标准对编译器实现做出的妥协。这种现象叫做“常量折叠(constant folding)”;与之相对的是不能直接使用,必须进行捕获的情况,通常称作“odr-used”。这两个概念比较复杂,在此不做过多展开。看下面的例子:
  281. >
  282. > ```c++
  283. > int Func1(const int& x) { return x; }
  284. > void Func2()
  285. > {
  286. > const int x = 4;
  287. > []()
  288. > {
  289. > int y = x; // OK, constant folding
  290. > int z = Func1(x); // Compile error! odr-used! x is not captured!
  291. > }();
  292. > }
  293. > ```
  294. >
  295. > 但是个别较老的编译器即使是 odr-used 也可能会编译通过
  296. #### lambda 表达式的修饰符 `mutable`
  297. lambda 表达式可以有一些修饰符,例如 `noexcept`、`mutable `等,这里仅介绍 `mutable`。
  298. lambda 表达式按值捕获变量时,捕获的变量默认是不可修改:
  299. ```c++
  300. int a = 4;
  301. auto f = [a]()
  302. {
  303. ++a; // Compile error: a cannot be modified!
  304. };
  305. ```
  306. 但是我们可以通过加 `mutable` 关键字让它达到这个目的:
  307. ```c++
  308. int a = 4;
  309. auto f = [a]() mutable
  310. {
  311. ++a; // OK
  312. cout << a << endl;
  313. };
  314. f(); //输出 5
  315. cout << a << endl; //输出 4
  316. ```
  317. 需要注意的是,按值捕获变量是生成了一个新的变量副本,而非原来的变量,所以在 lambda 外的 `a` 的值仍然是 `4`
  318. #### lambda 表达式的本质
  319. 本段内容仅是粗略地讲述,不做深入讨论。读者也可以跳过本块。
  320. 上面说了这么多语法规定,但是 lamdba 表达式究竟是什么?知道了这个可以帮助我们理解 lambda 表达式的这些规定。
  321. C++17 标准中如此定义 lambda 的类型:
  322. > The type of a *lambda-expression* (which is also the type of the closure object ) is a unique, unnamed non-union class type, called the closure type....
  323. lambda 表达式类型是一个独一无二的、没有名字的、并且不是联合体的类类型。我们把它叫做“**closure type**”。
  324. 后面还有一堆关于它性质的约束,这里就不展开了,大致上就是编译器可以自由决定它的很多性质,有兴趣的可以去翻阅《ISO/IEC 14882: 2017》第 8.1.5.1 款。
  325. 大体来看,一个 lamdba 表达式与一个类是大致上相同的。也就是说,lambda 表达式:
  326. ```c++
  327. int a = 0, b = 0;
  328. auto f = [a, &b](int x) { return a + b + x; }
  329. f(5);
  330. ```
  331. 和下面的代码大致相同:
  332. ```c++
  333. int a = 0, b = 0;
  334. class __lambda__
  335. {
  336. private:
  337. int a;
  338. int& b;
  339. public:
  340. __lambda__(int& a, int& b) : a(a), b(b) {}
  341. auto operator(int x) const { return a + b + x; }
  342. };
  343. __lambda__ f(a, b);
  344. f.operator()(5);
  345. ```
  346. 不过它们两个**并不完全相同**。首先,不同编译器的实现本身就有不同;另外,它们在语法上的规定也有一些差别。篇幅所限,在此不做过多展开。
  347. #### lambda 表达式的应用
  348. 看了上面这么多介绍,你可能要问:这东西能用什么用处?为什么不直接写个函数,或者是干脆不用 lambda 表达式而直接写在函数体里呢?有这个疑问是正常的。因为我上面给的例子都是可以不用 lambda 表达式就能轻松解决的。但是,lambda 表达式在很多应用场景具有不可替代的优势。最简单的例子,比如在局部,你要重复某些操作,但是另写一个函数又不是很方便,就可以用 lambda 表达式完成。此外,它最大的作用就是在函数式编程中,或者是其他需要回调函数的情况,以 lambda 表达式作为函数的参数以作为回调函数。在下面的教程中,例如多线程、智能指针,我们将会多次用到 lambda 表达式。届时你将会看到使用 lambda 表达式是多么的方便。
  349. #### 关于 lambda 表达式的其他说明
  350. lambda 表达式还有很多有趣之处,例如泛型 lambda、返回 lambda 表达式的 lamdba 表达式,此外 `decltype` 在 lambda 表达式中的使用也是光怪陆离……总之,lambda 表达式非常有趣。
  351. 到了这里,相信你对 lambda 表达式已经有了相当的理解,就让我们来做一道简单的练习吧(狗头)
  352. > 请给出下面程序的输出(该程序选自《ISO/IEC 14882: 2017 Programming Language --- C++》第 107 页):
  353. >
  354. > ```c++
  355. >#include <iostream>
  356. > using namespace std;
  357. >
  358. > int main()
  359. > {
  360. > int a = 1, b = 1, c = 1;
  361. > auto m1 = [a, &b, &c]() mutable
  362. > {
  363. > auto m2 = [a, b, &c]() mutable
  364. > {
  365. > cout << a << b << c;
  366. > a = 4; b = 4; c = 4;
  367. > };
  368. > a = 3; b = 3; c = 3;
  369. > m2();
  370. > };
  371. > a = 2; b = 2; c = 2;
  372. > m1();
  373. > cout << a << b << c << endl;
  374. > return 0;
  375. > }
  376. > ```
  377. > 相信聪明的你一下就看出了答案。没错,答案就是我们小学二年级学习的数字:**123234**!怎么样,你答对了吗?
  378. >
  379. 如果阅读本文之后你觉得 lambda 表达式很有趣,欢迎阅读 《ISO/IEC 14882: 2017 Programming Language --- C++》110~120 页,或点击进入网址:[cppreference_lambda](https://zh.cppreference.com/w/cpp/language/lambda) 获取更多信息。
  380. ### std::thread
  381. 头文件:`#include <thread>`。用于开启新的线程。示例代码:
  382. ```c++
  383. #include <iostream>
  384. #include <thread>
  385. #include <functional>
  386. void Func(int x, int& cnt)
  387. {
  388. for (int i = 0; i < 110; ++i)
  389. {
  390. std::cout << "In Func: " << x << std::endl;
  391. ++cnt;
  392. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  393. }
  394. }
  395. int main()
  396. {
  397. int cnt = 0;
  398. // 由于这种情况下函数的调用与传参不是同时的,提供参数在函数调用之前,因此以引用方式传递参数时需要用 std::ref
  399. std::thread thr(Func, 2021, std::ref(cnt));
  400. for (int i = 0; i < 50; ++i)
  401. {
  402. std::cout << "In main: " << 110 << std::endl;
  403. ++cnt;
  404. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  405. }
  406. thr.join(); // 等待子线程结束,在 thr 析构前若未 detach 则必须调用此函数,等待过程中主线程 main 被阻塞
  407. std::cout << "Count: " << cnt << std::endl;
  408. return 0;
  409. }
  410. ```
  411. 或者使用 lambda 表达式达到同样效果:
  412. ```c++
  413. #include <iostream>
  414. #include <thread>
  415. #include <functional>
  416. int main()
  417. {
  418. int cnt = 0, x = 2021;
  419. std::thread thr
  420. (
  421. [x, &cnt]()
  422. {
  423. for (int i = 0; i < 110; ++i)
  424. {
  425. std::cout << "In Func: " << x << std::endl;
  426. ++cnt;
  427. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  428. }
  429. }
  430. );
  431. for (int i = 0; i < 50; ++i)
  432. {
  433. std::cout << "In main: " << 110 << std::endl;
  434. ++cnt;
  435. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  436. }
  437. thr.join();
  438. std::cout << "Count: " << cnt << std::endl;
  439. return 0;
  440. }
  441. ```
  442. 如果不希望等待子线程结束,`main` 结束则程序结束,则可以构造临时对象调用 `detach` 函数:
  443. ```c++
  444. #include <iostream>
  445. #include <thread>
  446. #include <functional>
  447. int main()
  448. {
  449. int cnt = 0, x = 2021;
  450. std::thread
  451. (
  452. [x, &cnt]()
  453. {
  454. for (int i = 0; i < 110; ++i)
  455. {
  456. std::cout << "In Func: " << x << std::endl;
  457. ++cnt;
  458. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  459. }
  460. }
  461. ).detach();
  462. for (int i = 0; i < 50; ++i)
  463. {
  464. std::cout << "In main: " << 110 << std::endl;
  465. ++cnt;
  466. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  467. }
  468. std::cout << "Count: " << cnt << std::endl;
  469. return 0;
  470. }
  471. ```
  472. 更多内容请参看(点击进入):[cppreference_thread](https://en.cppreference.com/w/cpp/thread/thread)
  473. ### 智能指针
  474. #### 总述
  475. 头文件:`include <memory>`
  476. 智能指针是 C++ 标准库中对指针的封装,它的好处是可以不需要 `delete`,而自动对其指向的资源进行释放,这在一定程度上降低了 C++ 程序员管理内存的难度,但同时智能指针的使用也具有一定的技巧。
  477. 智能指针主要有三种:`shared_ptr`、`weak_ptr`、`unique_ptr`。
  478. #### `std::shared_ptr`
  479. ##### 概览
  480. `shared_ptr` 的用法最为灵活,内部实现方式是**引用计数**。即,它会记录有多少个 `shared_ptr` 正在指向某个资源,并当指向该资源的智能指针数为零时,调用相应的释放函数(默认为 `delete` 操作符)释放该资源。不过也需要注意,使用 `std::shared_ptr` 会比传统的指针带来额外的引用计数的开销,因此只有当后面将会介绍的 `std::unique_ptr` 无法满足要求时方可考虑 `std::shared_ptr`。
  481. 像 `new` 会在自由存储区动态获取一块内存并返回其一样,如果要动态分配一块内存并得到其智能指针,可以使用 `std::make_shared` 模板,例如:
  482. ```c++
  483. #include <memory>
  484. void Func()
  485. {
  486. int* p = new int(110); // 在自由存储区 new 一个 int 对象,初值为 110
  487. auto sp = std::make_shared<int>(110); // 在自由存储区 new 一个 int 对象,初值为 110
  488. // sp 被自动推导为 std::shared_ptr<int> 类型
  489. delete p; // 释放内存
  490. // 编译器调用 sp 的析构函数,并将其指向的 int 释放掉
  491. }
  492. ```
  493. 关于引用计数:
  494. ```cpp
  495. #include <memory>
  496. void Func()
  497. {
  498. int x = 110;
  499. {
  500. auto sp1 = std::make_shared<int>(x); // 得到一个 int,初值为 110。
  501. // 上述此语句执行过后,只有一个智能指针 sp1 指向这个 int,引用计数为 1
  502. {
  503. auto sp2 = sp1; // 构造一个智能指针 sp2,指向 sp1 指向的内存,并将引用计数+1
  504. // 故此处引用计数为2
  505. std::cout << *sp2 << std::endl; // 输出 110
  506. // 此处 sp2 生存期已到,调用 sp2 的析构函数,使引用计数-1,因此此时引用计数为1
  507. }
  508. // 此处 sp1 生命期也已经到了,调用 sp1 析构函数,引用计数再-1,故引用计数降为0
  509. // 也就是不再有智能指针指向它了,调用 delete 释放内存
  510. }
  511. }
  512. ```
  513. 将普通指针交给智能指针托管:
  514. ```cpp
  515. int* p = new int(110);
  516. int* q = new int(110);
  517. std::shared_ptr sp(p); // 把 p 指向的内存交给 sp 托管,此后 p 便不需要 delete,sp 析构时会自动释放
  518. std::shared_ptr sq; // sq 什么也不托管
  519. sq.reset(q); // 让 sq 托管 q
  520. //此后 p 与 q 便不需要再 delete
  521. ```
  522. 需要注意的是,这种写法是非常危险的,既可能导致 `p` 与 `q` 变为野指针,也可能造成重复 `delete`,我们应该更多使用 make_shared。
  523. ##### 自定义释放函数
  524. 之前说过 ,默认情况下是释放内存的函数是 `delete` 运算符,但有时我们并不希望这样。比如下面的几个情况:
  525. + 使用智能指针托管动态数组
  526. ```cpp
  527. #include <memory>
  528. void IntArrayDeleter(int* p) { delete[] p; }
  529. int main()
  530. {
  531. std::shared_ptr<int> sp(new int[10], IntArrayDeleter); // 让 IntArrayDeleter 作为释放资源的函数
  532. // sp 析构时自动调用 IntArrayDeleter 释放该 int 数组
  533. return 0;
  534. }
  535. // 或者利用 lambda 表达式:std::shared_ptr<int> sp(new int[10], [](int* p) { delete[] p; });
  536. ```
  537. + 释放系统资源
  538. 在编程过程中,难免与操作系统打交道,这时我们可能需要获取一系列的系统资源,并还给操作系统(实际上 `new` 和 `delete` 也就是一个例子)。一个比较有特色的例子就是 Windows API。在传统的 Win32 程序中,如果我们要在屏幕上进行绘制图形,我们首先需要获取设备的上下文信息,才能在设备上进行绘图。设想这样一个情景:我们有一个窗口,已经获得了指向这个窗口的句柄(即指针)`hWnd`,我们要在窗口上绘图,就要通过这个窗口句柄获取设备上下文信息。代码如下:
  539. ```c++
  540. HDC hdc; // DC: Device context,一个指向 DC 的句柄(HANDLE)
  541. hdc = GetDC(hWnd); // 获取设备上下文
  542. /*执行绘图操作*/
  543. ReleaseDC(hWnd, hdc); // 绘图完毕,将设备上下文资源释放,归还给 Windows 系统
  544. ```
  545. 使用智能指针对其进行托管,代码如下:
  546. ```c++
  547. // 使用 lambda 表达式写法(推荐)
  548. std::shared_ptr<void> sp(GetDC(hWnd), [hWnd](void* hdc) { ReleaseDC(hWnd, (HDC)hdc); });
  549. ```
  550. ```cpp
  551. // 不使用 lambda 表达式的写法:
  552. struct Releaser
  553. {
  554. HWND hWnd;
  555. Releaser(HWND hWnd) : hWnd(hWnd) {}
  556. void operator()(void* hdc)
  557. {
  558. ReleaseDC(hWnd, (HDC)hdc);
  559. }
  560. };
  561. void PaintFunc()
  562. {
  563. /*...*/
  564. std::shared_ptr<void> sp(GetDC(hWnd), Releaser(hWnd));
  565. /*...*/
  566. }
  567. ```
  568. ##### 常见的错误用法
  569. `std::shared_ptr` 虽然方便,但是也有一些错误用法,这个是常见的:
  570. ```c++
  571. #include <memory>
  572. void Func()
  573. {
  574. int* p = new int(110);
  575. std::shared_ptr<int> sp(p); // 让 sp 托管 p
  576. std::shared_ptr<int> sq(p); // 让 sq 托管 p
  577. // Runtime Error! 程序至此崩溃
  578. }
  579. ```
  580. 这是因为,只有复制构造函数里面才有使引用计数加1的操作。即当我们写 `std::shared_ptr<int> sq = sp` 的时候,确实引用计数变成了2,但是我们都用一个外部的裸指针 `p` 去初始化 `sp` 和 `sq`,智能指针并不能感知到它们托管的内存相同。所以 `sp` 和 `sq` 所托管的内存被看做是独立的。这样,当它们析构的时候,均会释放它们所指的内存,因此同一块内存被释放了两次,导致程序出错。所以个人还是推荐使用 `make_shared` ,而不是用裸指针去获取内存。
  581. 另一个著名的错误用法,请继续阅读 `std::weak_ptr`。
  582. #### `std::weak_ptr`
  583. 看完了上面的 `shared_ptr` 的讲述,相信你已经对使用智能指针胸有成竹了。一切都用 `shared_ptr`、`make_shared` 就万事大吉了嘛!但事情可能没那么简单。看下面的例子:
  584. ```c++
  585. #include <iostream>
  586. #include <memory>
  587. class B;
  588. class A
  589. {
  590. public:
  591. void SetB(const std::shared_ptr<B>& ipB)
  592. {
  593. pB = ipB;
  594. }
  595. private:
  596. std::shared_ptr<B> pB;
  597. };
  598. class B
  599. {
  600. public:
  601. void SetA(const std::shared_ptr<A>& ipA)
  602. {
  603. pA = ipA;
  604. }
  605. private:
  606. std::shared_ptr<A> pA;
  607. };
  608. void Func()
  609. {
  610. auto pA = std::make_shared<A>();
  611. auto pB = std::make_shared<B>();
  612. pA->SetB(pB);
  613. pB->SetA(pA);
  614. // 内存泄露!!!
  615. }
  616. /*...*/
  617. ```
  618. 太糟糕了!上面的 `pA` 指向的的对象和 `pB` 指向的对象一直到程序结束之前永远不会被释放!如果不相信,可以在它们的析构函数里输出些什么试一试。相信学习了引用计数的你,一定能想出来原因。我们就把它当作一道思考题作为练习:为什么这两个对象不会被释放呢?(提示:注意只有引用计数降为0的时候才会释放)
  619. 实际上,`std::shared_ptr` 并不是乱用的。它除了作为一个指针之外,还表明了一种逻辑上的归属关系。从逻辑上看,类的成员代表一种归属权的关系,类的成员属于这个类。拥有 `shared_ptr` 作为**成员**的对象,是对 `shared_ptr` 所指向的对象具有所有权的,`shared_ptr` 也是基于这个理念设计的。但是,有时候我们并不希望这是个所有权的关系,例如我们有双亲和孩子的指针作为“人”的成员,但是人与人之间是平等相待和谐共处的,我们不能说一个人是另一个人的附属品。这时候,`std::weak_ptr` 便应运而生了!
  620. `std::weak_ptr` 与 `shared_ptr` 的区别是,它指向一个资源,并不会增加引用计数。当指向一个资源的 `shared_ptr` 的数量为 0 的时候,即使还有 `weak_ptr` 在指,资源也会被释放掉。也是因此,`weak_ptr`也是存在悬垂指针的可能的,即它指向的资源已经被释放掉。 也是因此,`weak_ptr` 不允许直接地被解引用,必须先转换为相应的 `shared_ptr` 才能解引用,获取其所指的资源。它的用法如下:
  621. ```cpp
  622. auto sp = std::make_shared<int>(5);
  623. std::weak_ptr<int> wp = sp; // 正确,让 wp 指向 sp 指向的资源
  624. // std::shared_ptr<int> sp1 = wp; // 错误,weak_ptr 不能直接赋值给 shared_ptr
  625. /* Do something */
  626. if (wp.expired())
  627. {
  628. std::cout << "The resource has been released!" << std::endl;
  629. }
  630. else
  631. {
  632. // std::cout << *wp << std::endl; // Compile error! weak_ptr 不能直接使用!
  633. auto sp1 = wp.lock(); // 从 weak_ptr 中恢复出 shared_ptr,sp1 的类型为 std::shared_ptr<int>
  634. std::cout << *sp1 << std::endl;
  635. }
  636. ```
  637. 从类的设计本身来看,`weak_ptr` 不会增加引用计数;从逻辑上看,`weak_ptr` 描述了一种联系,即 `weak_ptr` 的拥有者与其指向的对象之间不是一种归属关系,而是一种较弱的联系。一个类的对象只需知道另一个类的对象是谁,而不对其拥有占有权,这时候用 `weak_ptr` 是合适的。
  638. 上面的 `A` 类和 `B` 类的问题,将 `A` 和 `B` 成员从 `shared_ptr` 换成 `weak_ptr` 就会解决内存泄露的问题了!
  639. #### `std::unique_ptr`
  640. `std::unique_ptr` 顾名思义,独有的指针,即资源只能同时为一个 `unique_ptr` 所占有,是基于 RAII 的思想设计的智能指针,并且相比于原始指针并不会带来任何额外开销,是智能指针的首选。它部分涉及到对象的生命期、右值引用与移动语义的问题,在此不做过多展开。
  641. 更多关于智能指针的知识,可以参考(点击进入):
  642. + [cppreference_shared_ptr](https://zh.cppreference.com/w/cpp/memory/shared_ptr)
  643. + [cppreference_weak_ptr](https://zh.cppreference.com/w/cpp/memory/weak_ptr)
  644. + [cppreference_unique_ptr](https://zh.cppreference.com/w/cpp/memory/unique_ptr)