mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-11-26 22:12:54 +08:00
- const README: rewrite the space-saving claim per issue #5 follow-ups (constant-expression const vs #define immediates; which const qualify as constant expressions) - const README: fix the class-section diagnosis per issue #338 (overload resolution picks the const overload; the restriction only surfaces once that overload is removed) - sizeof README: virtual-inheritance result is compiler-dependent (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246 - static README: new section on internal linkage / access restriction with anonymous-namespace comparison #142 - 10-day practice: full problem list table + fixed day links #136 - new design_pattern/singleton/singleton_default.hpp: reusable thread-safe CRTP singleton template, compile+concurrency tested #303
This commit is contained in:
59
site_extras/about.md
Normal file
59
site_extras/about.md
Normal file
@@ -0,0 +1,59 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/about/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 联系作者
|
||||
|
||||
我是开源社区的积极参与者,为[CPlusPlusThings](https://github.com/Light-City/CPlusPlusThings)、[Apache Arrow](https://github.com/apache/arrow)和[DuckDB](https://github.com/duckdb/duckdb)等项目做出了贡献。我热衷于促进开源计划的发展并支持协作生态系统。
|
||||
|
||||
我是一名全栈工程师。
|
||||
|
||||
我❤️后端工程师。
|
||||
|
||||
🖖 我主要将精力放在使用 C/Go/C++ 进行后端开发上。
|
||||
|
||||
我喜欢在以下平台写文章:
|
||||
|
||||
- [Medium](https://light-city.medium.com/)
|
||||
- [WeChat](https://mp.weixin.qq.com/s/5_Ms8bGbA-PWj5EwmTBaQA)
|
||||
- [ZhiHu](https://www.zhihu.com/people/francis-52-23/posts)
|
||||
- [BiliBili](https://space.bilibili.com/367439608?spm_id_from=333.337.0.0)
|
||||
|
||||
现在专注于数据库相关的工作,欢迎与我交流!
|
||||
|
||||
- 微信
|
||||
|
||||
搜索:gcxzhang
|
||||
|
||||
- 微信公众号
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/xq.jpg" height="200" width="200"><br>
|
||||
知识星球
|
||||
</th>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/wechat.jpg" height="200" width="200"><br>
|
||||
微信公众号
|
||||
</th>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
- 赞赏我
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/alipay.jpg" height="200" width="200"><br>
|
||||
支付宝
|
||||
</th>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/wechat.png" height="200" width="200"><br>
|
||||
微信
|
||||
</th>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
- 邮箱: 455954986@qq.com
|
||||
146
site_extras/cplusplus-things-overview.md
Normal file
146
site_extras/cplusplus-things-overview.md
Normal file
@@ -0,0 +1,146 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cplusplus-things-overview/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 项目概要
|
||||
|
||||
## 1. 项目概述
|
||||
|
||||
- 中文名:[**C++那些事**](https://github.com/Light-City/CPlusPlusThings)
|
||||
- 英文名:[**Stories About C Plus Plus or CPlusPlusThings**](https://github.com/Light-City/CPlusPlusThings)
|
||||
|
||||
**C++ 那些事** 是一个面向 C++ 初学者和进阶开发者的开源学习项目。该项目旨在帮助学习者从 C++ 的基础入门到高级进阶,涵盖从语法基础、面向对象编程、模板编程、STL 使用,到多线程并发、内存管理、性能优化等高级主题。此外,项目还深入分析了一些经典的开源库和框架的源码,帮助开发者更好地理解 C++ 在实际项目中的应用。
|
||||
|
||||
## 2. 项目目标
|
||||
|
||||
- **入门到进阶**:为初学者提供一个系统化的学习路径,帮助他们从零基础逐步掌握 C++ 的核心概念和高级特性。
|
||||
- **面试准备**:为求职者提供常见 C++ 面试题的解析和实战演练,帮助他们在面试中脱颖而出。
|
||||
- **源码分析**:通过分析经典开源项目的源码,帮助开发者深入理解 C++ 的设计模式和实现原理。
|
||||
- **多线程与并发**:深入探讨 C++ 中的多线程编程和并发控制,帮助开发者编写高效、安全的并发程序。
|
||||
- **性能优化**:介绍 C++ 中的性能优化技巧,帮助开发者编写高效的代码。
|
||||
|
||||
## 3. 项目内容
|
||||
|
||||
**C++ 那些事** 项目内容丰富,涵盖了 C++ 的各个方面,主要包括以下几个模块:
|
||||
|
||||
- **基础进阶**
|
||||
|
||||
- **关键字与特性**:如 `const`、`static`、`this`、`inline`、`sizeof`、`virtual`、`volatile`、`explicit`、`friend`、`using`、`::`、`enum`、`decltype` 等关键字的详细解析。
|
||||
- **函数与指针**:函数指针、纯虚函数和抽象类、`vptr_vtable` 等。
|
||||
- **数据结构**:`struct`、`union`、位域、引用与指针的区别等。
|
||||
- **C 实现 C++ 多态**:通过 C 语言实现 C++ 的多态特性。
|
||||
- **宏与断言**:宏的定义与使用、`assert` 的使用场景。
|
||||
|
||||
- **实战系列**
|
||||
|
||||
- **10 日狂练**:通过 10 天的密集练习,快速提升 C++ 编程能力。
|
||||
- **重点实战练习**:针对 C++ 中的重点难点进行实战演练,巩固所学知识。
|
||||
|
||||
- **STL 源码剖析**
|
||||
|
||||
- **容器**:`array`、`deque`、`queue`、`stack`、`list`、`vector`、`rb_tree`、`set`、`multiset`、`map`、`multimap`、`hashtable`、`unordered_map` 等容器的源码分析。
|
||||
- **迭代器与特性**:`iterator`、`traits`、`typename` 等。
|
||||
- **EBO 优化**:STL 设计中的空基类优化(EBO)技术。
|
||||
|
||||
- **C++2.0 新特性**
|
||||
|
||||
- **C++11 新特性**:如自动类型推导、Lambda 表达式、右值引用、智能指针等;另见站内 [C++11 专题](modern-cpp/cpp11/index.md)。
|
||||
- **C++17 / C++20**:[C++17 专题](modern-cpp/cpp17/index.md)、[C++20 专题](modern-cpp/cpp20/index.md)。
|
||||
|
||||
- **拓展专题**
|
||||
|
||||
- **语言机制深入**:mutable、const 全家桶、ABI、尾递归等(见导航「基础进阶 → 语言机制深入」)。
|
||||
- **内存与调试**、**性能测评**、**项目实战**、**阅读与技巧**:独立导航栏目,含 AddressSanitizer、Benchmark、pybind11、gRPC 等实战文。
|
||||
|
||||
- **设计模式**
|
||||
|
||||
- **常见设计模式**:如单例模式、工厂模式、观察者模式等在 C++ 中的应用。
|
||||
|
||||
- **并发编程**
|
||||
|
||||
- **多线程与多进程**:`std::thread`、`std::async`、`std::mutex`、`std::condition_variable` 等多线程编程技术。
|
||||
- **C++ Concurrency in Action**:深入探讨 C++ 中的并发编程模型与实践。
|
||||
|
||||
- **C++ 惯用法**
|
||||
|
||||
- **编程风格与惯用法**:探讨 C++ 中的常见编程风格与惯用法,帮助开发者写出更优雅的代码。
|
||||
|
||||
- **学习课程**
|
||||
|
||||
- **极客时间《现代 C++ 实战 30 讲》**:推荐学习资源,帮助开发者系统学习现代 C++。
|
||||
|
||||
- **工具篇**
|
||||
|
||||
- **调试与输出工具**:如 `dbg-macro`、`rr` 等调试工具的使用。
|
||||
- **容器快捷输出工具**:简化容器输出的工具。
|
||||
- **观察编译过程**:通过工具观察 C++ 代码的编译过程变化。
|
||||
|
||||
## 4. 项目特色
|
||||
|
||||
- **系统化学习路径**:从基础到进阶,内容循序渐进,适合不同层次的学习者。
|
||||
- **理论与实践结合**:不仅有理论知识的讲解,还有大量的代码示例和实战项目。
|
||||
- **源码深度分析**:通过分析经典开源项目的源码,帮助开发者深入理解 C++ 的设计与实现。
|
||||
- **多线程与并发**:深入探讨 C++ 中的并发编程,帮助开发者编写高效、安全的并发程序。
|
||||
- **面试导向**:提供常见面试题的解析,帮助求职者更好地准备面试。
|
||||
|
||||
## 5. 项目资源
|
||||
|
||||
- **在线学习网站**:[C++那些事](https://light-city.github.io/stories_things/)
|
||||
- **微信公众号**:[光城](https://mp.weixin.qq.com/s/5_Ms8bGbA-PWj5EwmTBaQA)
|
||||
- **B站视频**:[未来的光城](https://www.bilibili.com/video/BV1Rv4y1H7LB/?vd_source=bb6532dcd5b1d6b26125da900adb618e),项目内容同步至 B站,以视频形式展示,方便学习者观看。
|
||||
|
||||
## 6. 参与方式
|
||||
|
||||
[**C++那些事**](https://github.com/Light-City/CPlusPlusThings)是一个开源项目,欢迎各位开发者参与贡献。你可以通过以下方式参与:
|
||||
|
||||
- **Star 和 Fork**:如果你觉得项目对你有帮助,欢迎在 GitHub 上 Star 和 Fork 项目。
|
||||
- **提交 PR**:如果你有好的内容或改进建议,欢迎提交 Pull Request。
|
||||
- **反馈与建议**:如果你在使用过程中遇到问题或有任何建议,欢迎在项目的 Issue 区提出。
|
||||
|
||||
## 7. 项目未来规划
|
||||
|
||||
- **扩展更多高级主题**:如 C++20 新特性、元编程、编译期计算等。
|
||||
- **增加更多实战项目**:通过更多的实战项目,帮助开发者将所学知识应用到实际开发中。
|
||||
- **社区建设**:建立更活跃的社区,鼓励开发者之间的交流与分享。
|
||||
|
||||
## 8. 结语
|
||||
|
||||
[**C++那些事**](https://github.com/Light-City/CPlusPlusThings)是一个致力于帮助 C++ 学习者从入门到进阶的开源项目。无论你是初学者还是有一定经验的开发者,都可以在这里找到适合自己的学习资源。希望通过这个项目,能够帮助更多的人掌握 C++,并在实际开发中运用自如。
|
||||
|
||||
欢迎各位开发者 Star、Fork、PR,共同推动 C++ 社区的发展!
|
||||
|
||||
## 9. 关于作者
|
||||
|
||||
- **微信**:搜索 `gcxzhang`
|
||||
|
||||
- **微信公众号**
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/xq.jpg" height="200" width="200"><br>
|
||||
知识星球
|
||||
</th>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/wechat.jpg" height="200" width="200"><br>
|
||||
微信公众号
|
||||
</th>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
- **赞赏支持**
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/alipay.jpg" height="200" width="200"><br>
|
||||
支付宝
|
||||
</th>
|
||||
<th align="center" style="height=200 width="200">
|
||||
<img src="assets/images/wechat.png" height="200" width="200"><br>
|
||||
微信
|
||||
</th>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
121
site_extras/cpp-benchmarks-cpp-sso-benchmark.md
Normal file
121
site_extras/cpp-benchmarks-cpp-sso-benchmark.md
Normal file
@@ -0,0 +1,121 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-benchmarks/cpp-sso-benchmark/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ string SSO 性能测试
|
||||
|
||||
今天想问大家两个问题:
|
||||
|
||||
**1.下面代码性能上有没有区别?**
|
||||
|
||||
```cpp
|
||||
std::string s1("hello world hel");
|
||||
std::string s2("hello world helo");
|
||||
```
|
||||
|
||||
**2.sizeof(std::string)是多少?**
|
||||
|
||||
下面,我们来一起探索这两个问题。
|
||||
|
||||
由于这两个答案在g++(libstdc++)与clang(libc++)上的结果不一样,所以这里会分别进行分析。
|
||||
|
||||
## 1.g++(libstdc++)
|
||||
|
||||
g++的源码我们以g++-10为例,详细代码可以戳这个github地址,这里列出比较核心的代码。
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/devel/omp/gcc-10/libstdc%2B%2B-v3/include/bits/basic_string.h#L171
|
||||
|
||||
```cpp
|
||||
template<typename _CharT, typename _Traits, typename _Alloc>
|
||||
class basic_string {
|
||||
private:
|
||||
struct _Alloc_hider : allocator_type {
|
||||
pointer _M_p; // The actual data.
|
||||
};
|
||||
enum { __min_cap = 15 / sizeof(value_type) };
|
||||
_Alloc_hider _M_dataplus; // 8 bytes
|
||||
size_type __size_; // 8 bytes
|
||||
|
||||
union {
|
||||
_CharT _M_local_buf[_S_local_capacity + 1]; // 16 bytes
|
||||
size_type _M_allocated_capacity; // 8 bytes
|
||||
}; // 16 bytes
|
||||
}; // 32 bytes
|
||||
```
|
||||
|
||||
在上面代码中注释部分详细的列出了string占据的字节(注意:这里的value_type以char来计算,也就是sizeof(value_type) = 1)。
|
||||
|
||||
sizeof(string) = 8 + 8 + 16 = 32。
|
||||
|
||||
其中8字节ptr,8字节size,16字节union。
|
||||
|
||||
性能层面,这里实现了SSO,本地buffer会存储最多15个字符,当超过15字符便会分配在heap上,这里我写了一个benchmark来对比性能。
|
||||
|
||||
- 短字符串测试内容为:"hello world hel",总共15个字符。
|
||||
- 长字符串测试内容为:"hello world helo",总共为16个字符。
|
||||
|
||||
```
|
||||
std::string s1("hello world hel");
|
||||
std::string s2("hello world helo");
|
||||
```
|
||||
|
||||
可以看到性能差距非常大,仅仅一个字符会导致std::string性能差别这么大!
|
||||
|
||||
这里本质还是前面的SSO local buffer。
|
||||
|
||||
性能测试:https://quick-bench.com/q/s7pvDB_SwQyDCcZk50odAaYIzMc
|
||||
|
||||

|
||||
|
||||
## 2.clang++(libc++)
|
||||
|
||||
同理,我们以llvm-14为例,如果想要看完整代码戳下面的github地址即可,这里摘取出核心代码。
|
||||
|
||||
> https://github.com/llvm/llvm-project/blob/release/14.x/libcxx/include/string#L765
|
||||
|
||||
```cpp
|
||||
template<class _CharT, class _Traits, class _Allocator>
|
||||
class basic_string {
|
||||
private:
|
||||
struct __long {
|
||||
size_type __cap_; // 8 bytes
|
||||
size_type __size_; // 8 bytes
|
||||
pointer __data_; // 8 bytes
|
||||
};
|
||||
|
||||
enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
|
||||
(sizeof(__long) - 1)/sizeof(value_type) : 2};
|
||||
|
||||
struct __short {
|
||||
union {
|
||||
unsigned char __size_; // 1 bytes
|
||||
value_type __lx; // 1 bytes
|
||||
}; // 1 bytes
|
||||
value_type __data_[__min_cap]; // 23 bytes
|
||||
}; // 24 bytes
|
||||
|
||||
union __ulx {
|
||||
__long __lx; // 24 bytes
|
||||
__short __lxx; // 24 bytes
|
||||
}; // 24 bytes
|
||||
}
|
||||
```
|
||||
|
||||
在上面代码中注释部分详细的列出了string占据的字节(注意:这里的value_type以char来计算,也就是sizeof(value_type) = 1)。
|
||||
|
||||
sizeof(string) = union的大小,这个union是24字节,所以等于24。
|
||||
|
||||
而SSO,本地buffer存储的字符不超过22,当超过22个字符便会分配在heap上。
|
||||
|
||||
所以当我们使用与gcc同样的测试代码应用在clang上,我们便得到了不太一样的结果,即:long字符串的性能与short字符串的性能拆别不大。原因就是gcc的测试case都是在22个字符以内,都是短字符。
|
||||
|
||||
性能测试:https://quick-bench.com/q/nmLMqQZ31cmWBbbIFr2nHN2JL1k
|
||||
|
||||

|
||||
|
||||
当我们测试真正的长短字符串时,性能便会发生明显变化,趋势与gcc保持一致。
|
||||
|
||||
- 短字符串测试内容为:"hello world hello worl",总共22个字符。
|
||||
- 长字符串测试内容为:"hello world hello world",总共为23个字符。
|
||||
|
||||
性能测试:https://quick-bench.com/q/ujtMrtotEi6RrpfMDJ1UcSLFIJE
|
||||
|
||||

|
||||
27
site_extras/cpp-benchmarks-memcpy-vs-std-copy.md
Normal file
27
site_extras/cpp-benchmarks-memcpy-vs-std-copy.md
Normal file
@@ -0,0 +1,27 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-benchmarks/memcpy-vs-std-copy/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# memcpy 与 std::copy 性能对比
|
||||
|
||||
最近在做性能优化时,发现有一些代码用了std::copy,还有一些用了memcpy,两者在功能上其实类似,那么它们对性能影响是怎样的呢?
|
||||
|
||||
于是本篇文章将会探讨这两者的一些使用场景。
|
||||
|
||||
## memcpy:理论上有一些性能优势
|
||||
|
||||
从理论上讲,`memcpy`可能具有轻微的性能优势,原因在于其不同于`std::copy`的要求。`memcpy`在处理数据拷贝时可以忽略数据重叠的可能性,而`std::copy`需要处理一些不同的情况(底层memmove)。然而,这种性能差异在实际应用中往往难以察觉,特别是对于小规模的数据拷贝操作。
|
||||
|
||||
值得注意的是,`memcpy`只能用于处理C风格的POD结构,因此在处理非POD类型时并不是一个可行的选择。
|
||||
|
||||
这里使用quick-bench做了一个测评,可以看到性能并无太大差别。
|
||||
|
||||
> https://quick-bench.com/q/QER6YyI5f33kmqNqV7_Zdw8P5AE
|
||||
|
||||

|
||||
|
||||
## 如何选择?
|
||||
|
||||
在实际项目中,如何选择`memcpy`还是`std::copy`取决于具体的需求。如果处理的是POD类型,而且希望保持灵活性,那么选择`std::copy`是更为明智的选择。对于大多数应用场景,`std::copy`提供了更通用、更安全的数据拷贝方式。
|
||||
|
||||
然而,在追求极致性能的情况下,可以考虑使用`memcpy`,尤其是在处理大规模数据时。但在做出选择时,务必结合实际应用场景,并借助性能分析工具进行详细测试和优化。
|
||||
|
||||
总的来说,`memcpy`和`std::copy`都有各自的优势和劣势,我们需要根据项目的具体要求,在性能和灵活性之间做出权衡。在实践中,通常选择更安全和通用的`std::copy`是一个更可靠的选择。
|
||||
121
site_extras/cpp-benchmarks-polymorphism-crtp-variant-virtual.md
Normal file
121
site_extras/cpp-benchmarks-polymorphism-crtp-variant-virtual.md
Normal file
@@ -0,0 +1,121 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-benchmarks/polymorphism-crtp-variant-virtual/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 多态:虚函数、CRTP 与 variant
|
||||
|
||||
## C++多态性能测试:CRTP vs std::variant vs virtual
|
||||
|
||||
多态是面向对象编程的一个重要概念,它使得单一接口能够代表不同的类型。C++提供了几种实现多态性的方式,本文将会讨论三种场景的多态:
|
||||
|
||||
1. **虚函数**:在C++中实现多态性的传统方式是使用虚函数。这涉及使用基类和派生类来实现特定的实现。
|
||||
2. **std::variant**:在C++17中引入的std::variant,它实现了一种无需继承的多态性。
|
||||
3. **CRTP(Curiously Recurring Template Pattern)**:CRTP是一种比较特殊的技术,它通过模板的奇特递归模式实现多态性。
|
||||
|
||||
测试的组合场景如下:
|
||||
|
||||
- 单纯crtp
|
||||
- crtp + std::variant
|
||||
- virtual
|
||||
- std::variant + std::visit
|
||||
- std::variant + std::get_if
|
||||
- std::variant + std::holds_alternative
|
||||
|
||||
使用的编译器:
|
||||
|
||||
- gcc 13.2
|
||||
- clang17.0
|
||||
|
||||
完整测试代码已放置**星球**,这里贴一下关键代码
|
||||
|
||||
```cpp
|
||||
class Shape {
|
||||
public:
|
||||
virtual ~Shape() = default;
|
||||
virtual double area() const = 0;
|
||||
};
|
||||
|
||||
class Circle : public Shape
|
||||
class Rectangle : public Shape
|
||||
|
||||
|
||||
|
||||
// virtual
|
||||
static void BM_VirtualFunction(benchmark::State& state) {
|
||||
std::vector<std::unique_ptr<Shape>> shapes;
|
||||
shapes.reserve(1000);
|
||||
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
if (i % 2 == 0) {
|
||||
shapes.emplace_back(std::make_unique<Circle>(5.0));
|
||||
} else {
|
||||
shapes.emplace_back(std::make_unique<Rectangle>(4.0, 6.0));
|
||||
}
|
||||
}
|
||||
|
||||
for (auto _ : state) {
|
||||
double totalArea = 0.0;
|
||||
for (const auto& shape : shapes) {
|
||||
totalArea += shape->area();
|
||||
}
|
||||
benchmark::DoNotOptimize(totalArea);
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_VirtualFunction);
|
||||
|
||||
static void BM_VariantVisit(benchmark::State& state) {
|
||||
std::vector<std::variant<Circle, Rectangle>> shapes;
|
||||
shapes.reserve(1000);
|
||||
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
if (i % 2 == 0) {
|
||||
shapes.emplace_back(Circle(5.0));
|
||||
} else {
|
||||
shapes.emplace_back(Rectangle(4.0, 6.0));
|
||||
}
|
||||
}
|
||||
|
||||
for (auto _ : state) {
|
||||
double totalArea = 0.0;
|
||||
for (const auto& s : shapes) {
|
||||
totalArea += std::visit([](const auto& shape) { return shape.area(); }, s);
|
||||
}
|
||||
benchmark::DoNotOptimize(totalArea);
|
||||
}
|
||||
}
|
||||
static void BM_CRTPVariant(benchmark::State& state) {
|
||||
std::vector<ShapeVariant> shapes;
|
||||
shapes.reserve(1000);
|
||||
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
if (i % 2 == 0) {
|
||||
shapes.emplace_back(crtp_light::Circle(5.0));
|
||||
} else {
|
||||
shapes.emplace_back(crtp_light::Rectangle(4.0, 6.0));
|
||||
}
|
||||
}
|
||||
|
||||
for (auto _ : state) {
|
||||
double totalArea = 0.0;
|
||||
for (const auto& s : shapes) {
|
||||
totalArea += std::visit([](const auto& shape) { return shape.area(); }, s);
|
||||
}
|
||||
benchmark::DoNotOptimize(totalArea);
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_CRTPVariant);
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
测试结果1:gcc编译,可以看到virtual与std::variant性能差别不大,但是与crtp差别非常大。
|
||||
|
||||

|
||||
|
||||
测试结果2:clang编译,总体趋势类似gcc编译,只有crtp + std::variant性能明显回退,这个可能也是由于这里用了std::visit导致。
|
||||
|
||||

|
||||
|
||||
在A Tour of C++书中提到:
|
||||
|
||||
> This is basically equivalent to a virtual function call, but potentially faster. As with all claims of performance, this ‘‘potentially faster’’ should be verified by measurements when performance is critical. For most uses, the difference in performance is insignificant.
|
||||
|
||||
与本次测试基本符合。
|
||||
97
site_extras/cpp-concurrency-cpp-deadlock-debugging.md
Normal file
97
site_extras/cpp-concurrency-cpp-deadlock-debugging.md
Normal file
@@ -0,0 +1,97 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/cpp-deadlock-debugging/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 死锁排查
|
||||
|
||||
## C++如何排查并发编程死锁问题?
|
||||
|
||||
最近在Apache arrow里面写一个支持并行的算子:nested loop join,然后既然涉及到并行,这里就会遇到大家常说的死锁问题,假设你碰到了死锁问题,如何调试与定位呢?
|
||||
|
||||
那这便是本篇目标,帮助你快速掌握并发编程:死锁检测与死锁调试问题,非常的干,好了进行正文。
|
||||
|
||||
## 1.引入
|
||||
|
||||
为了更好的讲解死锁,我们用一个程序来引入。
|
||||
|
||||
```cpp
|
||||
std::mutex gMutex;
|
||||
|
||||
int t2() {
|
||||
std::lock_guard<std::mutex> m(gMutex);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int t1() {
|
||||
std::lock_guard<std::mutex> l(gMutex);
|
||||
return t2();
|
||||
}
|
||||
```
|
||||
|
||||
相信看这个程序,大家都会觉得有问题,死锁了!问题出在`t1()`函数和`t2()`函数中都对全局的互斥锁`gMutex`进行了加锁操作,但是`t1()`函数在加锁后调用了`t2()`函数,而`t2()`函数内部又试图再次对`gMutex`进行加锁。
|
||||
|
||||
t1锁已经加上了,但还没释放,t2又去加锁,两个人都在等待谁先释放,进入了死循环,实际在项目中代码并不会如这里这么简单,非常的复杂,例如:我在Apache arrow中写的代码是这样:
|
||||
|
||||
```cpp
|
||||
Status OnBuildSideFinished(size_t thread_index) {
|
||||
std::lock_guard<std::mutex> guard(probe_side_mutex_);
|
||||
// do something
|
||||
accumulate_build_ready_ = true;
|
||||
return scheduler_->StartTaskGroup(thread_index,task_group_probe_,queued_batches_to_probe_.batch_count());
|
||||
}
|
||||
```
|
||||
|
||||
你看这个代码比上面的场景就复杂多了,嵌套了至少5层堆栈,剩余代码还没贴出来,但是这两个本质都是一个死锁模型。
|
||||
|
||||
## 2.调试
|
||||
|
||||
讲解了死锁模型之后,碰到这种问题,如何定位呢?
|
||||
|
||||
这里可以采用两种办法,第一种直接运行程序,然后gdb上去。
|
||||
|
||||
例如:
|
||||
|
||||
```
|
||||
./a.out
|
||||
```
|
||||
|
||||
然后找到进程号后:
|
||||
|
||||
```
|
||||
gdb -p xxx
|
||||
```
|
||||
|
||||
此时我们可以得到及格正在等待的线程。
|
||||
|
||||
```cpp
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
* 1 Thread 0x7ffff7fe2740 (LWP 32301) "a.out" 0x00007ffff7bc8017 in pthread_join () from /lib64/libpthread.so.0
|
||||
2 Thread 0x7ffff6fd0700 (LWP 32305) "a.out" 0x00007ffff7bcd54d in __lll_lock_wait () from /lib64/libpthread.so.0
|
||||
```
|
||||
|
||||
然后去看`__lll_lock_wait`的堆栈,例如这里我看了2号线程,然后查看堆栈得到t1与t2的行号,直接可以定位到哪里出了问题,非常的直观!
|
||||
|
||||
|
||||
|
||||
除了这种方式之外,还可以直接gdb上去运行程序,此时会卡死,然后ctrl + c杀掉之后也是可以跟上面一样的内容。
|
||||
|
||||
例如:
|
||||
|
||||
```
|
||||
(gdb) r
|
||||
Starting program: /home/light/a.out
|
||||
Missing separate debuginfos, use: debuginfo-install glibc-2.17-326.el7_9.x86_64
|
||||
[Thread debugging using libthread_db enabled]
|
||||
Using host libthread_db library "/lib64/libthread_db.so.1".
|
||||
Hello World!
|
||||
[New Thread 0x7ffff6fd0700 (LWP 32305)]
|
||||
^C
|
||||
Thread 1 "a.out" received signal SIGINT, Interrupt.
|
||||
0x00007ffff7bc8017 in pthread_join () from /lib64/libpthread.so.0
|
||||
Missing separate debuginfos, use: debuginfo-install libgcc-4.8.5-44.el7.x86_64 libstdc++-4.8.5-44.el7.x86_64
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
* 1 Thread 0x7ffff7fe2740 (LWP 32301) "a.out" 0x00007ffff7bc8017 in pthread_join () from /lib64/libpthread.so.0
|
||||
2 Thread 0x7ffff6fd0700 (LWP 32305) "a.out" 0x00007ffff7bcd54d in __lll_lock_wait () from /lib64/libpthread.so.0
|
||||
```
|
||||
|
||||
好了,本节就讲这么多,感兴趣的欢迎转发这篇硬核文章!于此同时,推荐一下自己的**线程池项目**,个人用视频讲解了这个项目,同时配上docker一键部署(这一期的视频,后面打算给大家录制一下),感兴趣的联系我即可。
|
||||
174
site_extras/cpp-concurrency-cpp-simd.md
Normal file
174
site_extras/cpp-concurrency-cpp-simd.md
Normal file
@@ -0,0 +1,174 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/cpp-simd/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ SIMD 向量化
|
||||
|
||||
最近在看相关向量化的内容,看起来有点头大,借此机会,学习一下高性能SIMD编程。
|
||||
|
||||
SIMD全称single-instruction multiple-data,单指令多数据。
|
||||
|
||||
在传统的计算机架构中,CPU一次只能处理一个数据元素。但是,许多任务涉及对大量数据执行相同的操作,例如对数组中的所有元素进行加法、乘法或逻辑操作等。SIMD编程通过向CPU提供专门的指令集,使得CPU能够同时对多个数据元素执行相同的操作。
|
||||
|
||||
这种处理方式特别适合涉及向量、矩阵、图像、音频和视频等数据的计算。
|
||||
|
||||
目前比较常用的有SSE、SSE2、AVX128、AVX256、AVX512。
|
||||
|
||||
本节,将简单学习一下AVX512的一些操作,操作比较多,这里只是引入一些。
|
||||
|
||||
## 1.术语
|
||||
|
||||
首先第一个问题便是,simd编程的代码跟平时写的代码长相不大一样,各种下划线以及命名,完全看不懂,如何理解呢?
|
||||
|
||||
诸如:
|
||||
|
||||
- _mm512_set1_ps
|
||||
|
||||
Broadcast single-precision (32-bit) floating-point value a to all elements of dst.
|
||||
|
||||
- _mm512_set1_epi32
|
||||
|
||||
Broadcast 32-bit integer a to all elements of dst.
|
||||
|
||||
于是,找到了下面这个表格:
|
||||
|
||||
| Abbreviation | Full Name | C/C++ Equivalent |
|
||||
| ------------ | ------------------------------ | ---------------- |
|
||||
| ps | packed single-precision | float |
|
||||
| ph | packed half-precision | None* |
|
||||
| pd | packed double-precision | double |
|
||||
| pch | packed half-precision complex | None* |
|
||||
| pi8 | packed 8-bit integer | int8_t |
|
||||
| pi16 | packed 16-bit integer | int16_t |
|
||||
| pi32 | packed 32-bit integer | int32_t |
|
||||
| epi8 | extended packed 8-bit integer | int8_t |
|
||||
| epi16 | extended packed 16-bit integer | int16_t |
|
||||
| epi32 | extended packed 32-bit integer | int32_t |
|
||||
| epi64 | extended packed 64-bit integer | int64_t |
|
||||
| epi64x | extended packed 64-bit integer | int64_t |
|
||||
|
||||
> https://stackoverflow.com/questions/70911872/what-are-the-names-and-meanings-of-the-intrinsic-vector-element-types-like-epi6
|
||||
|
||||
再比如:
|
||||
|
||||
_mm512_mask_load_ps
|
||||
|
||||
_mm512_mask_loadu_ps
|
||||
|
||||
u表示unordered,表示加载无序,当使用 `_mm512_mask_loadu_ps` 函数加载内存中的数据时,不会执行对内存地址的任何对齐要求。而_mm512_mask_load_ps要求满足 64 字节对齐要求。
|
||||
|
||||
这样对照着学习,非常快的便可以知道每个接口的含义了。
|
||||
|
||||
相关API可以看看Interl Intrinsics Guide。
|
||||
|
||||
> https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html
|
||||
|
||||
## 2.实际例子
|
||||
|
||||
### 2.1 求最小值
|
||||
|
||||
对于512位,我们可以存储16个32位float。
|
||||
|
||||
```cpp
|
||||
static inline rf_512 load(float* ptr) { return _mm512_loadu_ps(ptr); }
|
||||
float a[width] = {1.0, 2.0, 3.0, 22.0, 5.0, 17.0, 9.0, 8.0,
|
||||
9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
|
||||
float b[width] = {3.3, 6.2, 5.3, 4.4, 5.5, 6.6, 7.7, 8.8,
|
||||
9.9, 10.10, 21.11, 12.12, 13.13, 14.14, 15.0, 16.16};
|
||||
rf_512 data = minimum(load(a), load(b));
|
||||
```
|
||||
|
||||
于是我们可以快速得到:
|
||||
|
||||
```cpp
|
||||
1 2 3 4.4 5 6.6 7.7 8 9 10 11 12 13 14 15 16
|
||||
```
|
||||
|
||||
## 2.2 快速打乱数据顺序
|
||||
|
||||
对于输入数据是
|
||||
|
||||
```
|
||||
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
```
|
||||
|
||||
我们可以快速得到:
|
||||
|
||||
```cpp
|
||||
16.16 2 14.14 13.13 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
```
|
||||
|
||||
对应实现:
|
||||
|
||||
```cpp
|
||||
static inline rf_512 permutexvar(ri_512 idx, rf_512 src) {
|
||||
return _mm512_permutexvar_ps(idx, src);
|
||||
}
|
||||
/*
|
||||
raw data: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
shuffle data: 16.16 2 14.14 13.13 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
*/
|
||||
void print_permutexvar_mask() {
|
||||
float a[width] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
|
||||
9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
|
||||
float b[width] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8,
|
||||
9.9, 10.10, 11.11, 12.12, 13.13, 14.14, 15.0, 16.16};
|
||||
mask_type mask = make_bit_mask<1, 0, 1, 1, 0>();
|
||||
int idx_array[width] = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
|
||||
ri_512 idx = _mm512_loadu_si512((__m512i*)idx_array);
|
||||
rf_512 result = permutexvar_mask(load(a), mask, idx, load(b));
|
||||
float result_arr[width];
|
||||
store(result, result_arr);
|
||||
std::cout << "raw data: ";
|
||||
for (int i = 0; i < width; i++) {
|
||||
std::cout << a[i] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
|
||||
std::cout << "shuffle data: ";
|
||||
for (int i = 0; i < width; i++) {
|
||||
std::cout << result_arr[i] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 旋转
|
||||
|
||||
对于一个数组:
|
||||
|
||||
```
|
||||
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
||||
```
|
||||
|
||||
我们可以旋转得到:
|
||||
|
||||
```
|
||||
4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13
|
||||
```
|
||||
|
||||
也就是rotate down or rotate up。
|
||||
|
||||
在这里,我们可以这样实现:
|
||||
|
||||
```cpp
|
||||
rf_512 rotateGeneral(float* arr, int s) {
|
||||
int idx_array[width];
|
||||
for (int i = 0; i < width; i++) {
|
||||
idx_array[i] = (i + s) % width;
|
||||
}
|
||||
ri_512 idx = _mm512_loadu_si512((__m512i*)idx_array);
|
||||
rf_512 result = permutexvar(idx, load(arr));
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
等等,还有其他的例子,可以发现通过使用simd,我们可以实现一些非常有趣的算法,加速对数组,批量数据的处理。
|
||||
|
||||
后面会继续学习simd,一起加油吧~
|
||||
|
||||
注:本节的完整示例已在星球更新,谢谢~
|
||||
145
site_extras/cpp-concurrency-cpp17-parallel-stl.md
Normal file
145
site_extras/cpp-concurrency-cpp17-parallel-stl.md
Normal file
@@ -0,0 +1,145 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/cpp17-parallel-stl/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 并行 STL
|
||||
|
||||
## 1.各个编译器支持进度
|
||||
|
||||
不同编译器对并行算法库的支持,如下:
|
||||
|
||||
> https://en.cppreference.com/w/cpp/compiler_support/17#C.2B.2B17_library_features
|
||||
|
||||
可以看到gcc9之后就支持了,clang目前支持还不完全,自己也本地测了一下确实不支持。
|
||||
|
||||

|
||||
|
||||
其支持的算法包括:
|
||||
|
||||

|
||||
|
||||
> https://en.cppreference.com/w/cpp/experimental/parallelism
|
||||
|
||||
## 2.并行算法库要求
|
||||
|
||||
gcc9以后便可以使用并行算法库了,我们可以看一下下面的gcc-9文档。
|
||||
|
||||
> https://gcc.gnu.org/gcc-9/changes.html
|
||||
|
||||
其中,提到一个非常重要的信息:**需要tbb支持**。
|
||||
|
||||

|
||||
|
||||
TBB是由英特尔(Intel)公司开发的一个用于并行编程的 C++ 库。TBB 旨在简化多核处理器上的并行软件开发,提供了一套抽象和模型,使程序员能够更容易地实现并行算法。
|
||||
|
||||
1.C++17当中使用并行算法库的前提必须得安装tbb,那如果不安装tbb会怎样呢?
|
||||
|
||||
我自己实测就是可以编译与运行,只是没有任何加速,跟原来非并行跑出来的结果是一样的。
|
||||
|
||||
2.TBB如何安装呢?
|
||||
|
||||
一个是官方的tbb,叫做oneTBB。
|
||||
|
||||
> https://github.com/oneapi-src/oneTBB
|
||||
|
||||
另一个是其他人写的tbb,叫做tbb。
|
||||
|
||||
> https://github.com/wjakob/tbb
|
||||
|
||||
区别在于添加了基于 CMake 的构建系统。
|
||||
|
||||
现在官方也是支持cmake ,所以建议去使用官方的吧。
|
||||
|
||||
编译也是非常简单:
|
||||
|
||||
```
|
||||
mkdir build && cmake ..
|
||||
make -j8
|
||||
make install
|
||||
```
|
||||
|
||||
## 3.如何使用
|
||||
|
||||
相比于传统的STL使用又有哪些改变呢?
|
||||
|
||||
**1.接口层面**
|
||||
|
||||
其实比较简单,例如 sort原来是:
|
||||
|
||||
```cpp
|
||||
std::sort(begin, end, comp);
|
||||
```
|
||||
|
||||
现在变为:
|
||||
|
||||
```
|
||||
std::sort(exe_policy, begin, end, comp);
|
||||
```
|
||||
|
||||
只需要添加执行策略(execution policy),有三个选项:
|
||||
|
||||
1. **`std::execution::seq`(顺序执行):**
|
||||
- 这是默认的执行策略,也就是说,如果你没有明确指定执行策略,算法将使用顺序执行。
|
||||
- 算法将按照顺序依次处理元素,不涉及并行处理。
|
||||
2. **`std::execution::par`(并行执行):**
|
||||
- 使用这个执行策略将启用并行执行。算法会尝试以并行的方式处理元素,充分利用多核处理器。
|
||||
3. **`std::execution::par_unseq`(并行和向量化执行):**
|
||||
- 这个执行策略允许算法在并行的同时进行向量化(vectorization),这意味着可以利用 SIMD(Single Instruction, Multiple Data)指令集进行并行向量化操作。
|
||||
- 与 `std::execution::par` 不同,`par_unseq` 在能够并行处理的同时还允许矢量化处理,从而更充分地利用硬件的并行和向量化能力。
|
||||
|
||||
**2.头文件层面**
|
||||
|
||||
必须要引入:
|
||||
|
||||
```cpp
|
||||
#include <algorithm>
|
||||
#include <execution>
|
||||
```
|
||||
|
||||
如果有tbb的操作,可以引入tbb的头文件,例如:设置线程数。
|
||||
|
||||
**3.编译层面**
|
||||
|
||||
编译时需要指定链接信息,例如:
|
||||
|
||||
```cpp
|
||||
g++ -O3 -std=c++17 -Wall -Wextra -pedantic -I/usr/local/include/tbb -L /usr/local/lib/ -o main.out main.cc -ltbb
|
||||
```
|
||||
|
||||
## 4.性能测试
|
||||
|
||||
最近在做sort相关的工作,想看看merge与sort的性能,所以写了个benchmark,逻辑如下:
|
||||
|
||||
- 串行sort vs 并行sort(par策略)
|
||||
|
||||
- 串行merge vs 并行merge(par策略)
|
||||
|
||||
数据范围:
|
||||
|
||||
```cpp
|
||||
BENCHMARK(BM_ParallelSort)->Arg(16384)->Arg(16384000)->Arg(163840000);
|
||||
```
|
||||
|
||||
下面的测试结果将采用tbb默认线程调度策略。
|
||||
|
||||
**对比组1:并行Sort/串行Sort详细数据与加速比**
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
**对比组2:并行Merge/串行Merge详细数据与加速比**
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
tbb文档:
|
||||
|
||||
> https://oneapi-src.github.io/oneTBB/index.html
|
||||
|
||||
如果要设置线程数,可以这样操作:
|
||||
|
||||
```cpp
|
||||
#include <tbb/tbb.h>
|
||||
|
||||
tbb::task_scheduler_init init(16);
|
||||
```
|
||||
54
site_extras/cpp-concurrency-false-sharing-cache-line.md
Normal file
54
site_extras/cpp-concurrency-false-sharing-cache-line.md
Normal file
@@ -0,0 +1,54 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/false-sharing-cache-line/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ False Sharing 与缓存行
|
||||
|
||||
最近看到一段代码,手动做的对齐,于是研究一下不对齐又会带来什么影响?
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
class AtomicWithPadding {
|
||||
private:
|
||||
static constexpr int kCacheLineSize = 64;
|
||||
uint8_t padding_before[kCacheLineSize];
|
||||
|
||||
public:
|
||||
std::atomic<T> value;
|
||||
|
||||
private:
|
||||
uint8_t padding_after[kCacheLineSize];
|
||||
};
|
||||
```
|
||||
|
||||
这里便引出了大家面试的必考点:
|
||||
|
||||
- Cache line
|
||||
|
||||
于是有下面几个面试问题,你能答上来?
|
||||
|
||||
- 什么是cache line?
|
||||
- 什么是MESI协议?
|
||||
- 什么是False sharing?
|
||||
- C++里面如何保证避免False sharing?
|
||||
- 避免False sharing可以带来什么好处?
|
||||
- 你知道C++17之后提供了哪两个变量解决这个问题?
|
||||
|
||||
于是,找了个性能测试,大概实现是:
|
||||
|
||||
- 定义4个变量,a、b、c、d,多线程进行共享
|
||||
- 另外是对这四个变量对齐,然后开n个线程去调度。
|
||||
|
||||
下面是benchmark:
|
||||
|
||||
```cpp
|
||||
------------------------------------------------------------------
|
||||
Benchmark Time CPU Iterations
|
||||
------------------------------------------------------------------
|
||||
singleThread 4.05 ms 4.04 ms 133
|
||||
directSharing/real_time 8.78 ms 0.069 ms 77
|
||||
falseSharing/real_time 8.81 ms 0.083 ms 74
|
||||
noSharing/real_time 1.16 ms 0.071 ms 578
|
||||
```
|
||||
|
||||
可以看到noSharing得到了非常好的效果!缓存命中率大大提高,当然这里用perf分析一下是更好的,可以看看L1 cache miss。
|
||||
|
||||
以上答案在知识星球已更新,欢迎一起探讨,留言区交流,谢谢~
|
||||
137
site_extras/cpp-concurrency-gdb-multi-thread-debug.md
Normal file
137
site_extras/cpp-concurrency-gdb-multi-thread-debug.md
Normal file
@@ -0,0 +1,137 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/gdb-multi-thread-debug/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# GDB 多线程 All-Stop 调试
|
||||
|
||||
当我们使用gdb调试多线程程序时,线程可以在任何时间执行,当我们想尝试调试某一个线程的时候(例如:next),会导致切换到其他线程,不符合我们在当前线程切到下一行的预期。
|
||||
|
||||
```cpp
|
||||
Thread 2 "arrow-compute-n" hit Breakpoint 1, arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5ba840, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
399 size_t thread_index = thread_indexer_();
|
||||
(gdb) n
|
||||
[Switching to Thread 0x7ffff2c08700 (LWP 29121)]
|
||||
|
||||
Thread 3 "arrow-compute-n" hit Breakpoint 1, arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
399 size_t thread_index = thread_indexer_();
|
||||
```
|
||||
|
||||
此时我们需要怎么做呢?
|
||||
|
||||
那便是今天要引入的调度器锁定(scheduler-locking)。GDB 无法锁步执行所有线程。由于线程调度取决于你调试目标的操作系统(而不是由 GDB 控制),因此在当前线程完成单步操作时,其他线程可能执行多个语句。此外,一般来说,当程序停止时,其他线程停在语句的中间,而不是在清晰的语句边界处停止。甚至在继续或单步执行后,你可能会发现你的程序停在另一个线程中。每当其他线程在第一个线程完成你请求的操作之前遇到断点、信号或异常时,就会发生这种情况。
|
||||
|
||||
而通过gdb提供的scheduler-locking可以帮助你锁定调度器以仅允许单个线程运行来修改 GDB 的默认行为。
|
||||
|
||||
默认情况下scheduler-locking值等于replay
|
||||
|
||||
```
|
||||
(gdb) show scheduler-locking
|
||||
Mode for locking scheduler during execution is "replay".
|
||||
```
|
||||
|
||||
在回放模式下的行为类似于on,在记录模式下或正常执行期间的行为类似于关闭。这是默认模式。
|
||||
|
||||
- on
|
||||
|
||||
例如执行`t 2`会切换到线程2上面,此时设置on会只在当前线程进行调试。
|
||||
|
||||
- off
|
||||
|
||||
与on相反,没有锁定,任何线程随时都可以运行。
|
||||
|
||||
- step
|
||||
|
||||
在单步执行时的行为类似于打开,否则类似于关闭。当你step时,除了当前线程之外的线程永远不会有机会运行,而当你使用像`continue`、`until`或`finish`这样的命令时,它们完全可以运行。
|
||||
|
||||
例如:next、step这种会在你想要的进程内进行调试,其他线程hang住;contine之类的会让所有的线程运行。
|
||||
|
||||
## 示例
|
||||
|
||||
可以看到当设置step时,continue会在线程之间切换。
|
||||
|
||||
```
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
1 Thread 0x7ffff7e88780 (LWP 31464) "arrow-compute-n" 0x00007ffff37e3de2 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
|
||||
2 Thread 0x7ffff3409700 (LWP 31494) "arrow-compute-n" arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
* 3 Thread 0x7ffff2c08700 (LWP 31495) "arrow-compute-n" arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
(gdb) c
|
||||
Continuing.
|
||||
[Switching to Thread 0x7ffff3409700 (LWP 31494)]
|
||||
|
||||
Thread 2 "arrow-compute-n" hit Breakpoint 1, arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
399 size_t thread_index = thread_indexer_();
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
1 Thread 0x7ffff7e88780 (LWP 31464) "arrow-compute-n" 0x00007ffff37e3de2 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
|
||||
* 2 Thread 0x7ffff3409700 (LWP 31494) "arrow-compute-n" arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
3 Thread 0x7ffff2c08700 (LWP 31495) "arrow-compute-n" 0x00007ffff605a372 in arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5bb060, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
```
|
||||
|
||||
然后再continue会进入到下一个断点:
|
||||
|
||||
```cpp
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
1 Thread 0x7ffff7e88780 (LWP 31464) "arrow-compute-n" 0x00007ffff37e3a35 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
|
||||
2 Thread 0x7ffff3409700 (LWP 31494) "arrow-compute-n" 0x00007ffff5781b50 in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch(unsigned long, arrow::compute::ExecBatch)@plt ()
|
||||
from /code/arrow/cpp/build/debug/libarrow.so.200
|
||||
* 3 Thread 0x7ffff2c08700 (LWP 31495) "arrow-compute-n" 0x00007ffff5781b50 in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch(unsigned long, arrow::compute::ExecBatch)@plt ()
|
||||
from /code/arrow/cpp/build/debug/libarrow.so.200
|
||||
(gdb) c
|
||||
Continuing.
|
||||
[Switching to Thread 0x7ffff3409700 (LWP 31494)]
|
||||
|
||||
Thread 2 "arrow-compute-n" hit Breakpoint 3, 0x00007ffff5781b50 in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch(unsigned long, arrow::compute::ExecBatch)@plt ()
|
||||
from /code/arrow/cpp/build/debug/libarrow.so.200
|
||||
(gdb) info threads
|
||||
Id Target Id Frame
|
||||
1 Thread 0x7ffff7e88780 (LWP 31464) "arrow-compute-n" 0x00007ffff37e3a35 in pthread_cond_wait@@GLIBC_2.3.2 () from /lib64/libpthread.so.0
|
||||
* 2 Thread 0x7ffff3409700 (LWP 31494) "arrow-compute-n" 0x00007ffff5781b50 in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch(unsigned long, arrow::compute::ExecBatch)@plt ()
|
||||
from /code/arrow/cpp/build/debug/libarrow.so.200
|
||||
3 Thread 0x7ffff2c08700 (LWP 31495) "arrow-compute-n" 0x00007ffff5781b56 in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch(unsigned long, arrow::compute::ExecBatch)@plt ()
|
||||
from /code/arrow/cpp/build/debug/libarrow.so.200
|
||||
```
|
||||
|
||||
可以看到线程之间切换,如果是想在线程内,可以直接next,例如:
|
||||
|
||||
```cpp
|
||||
(gdb) t 2
|
||||
[Switching to thread 2 (Thread 0x7ffff3409700 (LWP 32396))]
|
||||
#0 0x00007ffff605ae0d in arrow::compute::NestedLoopJoinNode::OnBuildSideBatch (this=0x5bbf90, thread_index=1, batch=...) at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:487
|
||||
487 if (!batch.length) {
|
||||
(gdb) n
|
||||
490 std::lock_guard<std::mutex> guard(build_side_mutex_);
|
||||
(gdb) n
|
||||
491 build_accumulator_.InsertBatch(std::move(batch));
|
||||
```
|
||||
|
||||
如果是执行print操作,引起了函数调用,会停止,输出不了我们符合预期的结果。
|
||||
|
||||
```cpp
|
||||
(gdb) p batch.ToString()
|
||||
[Switching to Thread 0x7ffff2c08700 (LWP 32397)]
|
||||
|
||||
Thread 3 "arrow-compute-n" hit Breakpoint 1, arrow::compute::NestedLoopJoinNode::InputReceived (this=0x5bbf90, input=0x5ba840, batch=...)
|
||||
at /code/arrow/cpp/src/arrow/compute/exec/nested_loop_node.cc:399
|
||||
399 size_t thread_index = thread_indexer_();
|
||||
The program stopped in another thread while making a function call from GDB.
|
||||
Evaluation of the expression containing the function
|
||||
(arrow::compute::ExecBatch::ToString() const) will be abandoned.
|
||||
When the function is done executing, GDB will silently stop.
|
||||
```
|
||||
|
||||
我们此时可以设置on,此时便可以进行print了!
|
||||
|
||||
```
|
||||
(gdb) set scheduler-locking on
|
||||
(gdb) p batch.ToString()
|
||||
$2 = "ExecBatch\n # Rows: 2\n 0: Array[null,4]\n 1: Array[true,false]\n"
|
||||
```
|
||||
|
||||
> https://sourceware.org/gdb/current/onlinedocs/gdb.html/All_002dStop-Mode.html
|
||||
77
site_extras/cpp-concurrency-helgrind-concurrency-check.md
Normal file
77
site_extras/cpp-concurrency-helgrind-concurrency-check.md
Normal file
@@ -0,0 +1,77 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/helgrind-concurrency-check/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Helgrind 并发错误检测
|
||||
|
||||
## C++那些事之helgrind并发编程检测
|
||||
|
||||
通常我们在写多线程程序的时候很容易遇到两个问题:
|
||||
|
||||
- 死锁了,不知道什么原因导致
|
||||
- 数据不一致,多个线程锁用错了
|
||||
|
||||
那么有没有工具来检测这两种场景呢
|
||||
|
||||
答案是有的,我们可以使用valgrind的helgrind工具检测这两个问题,为了使本文讲解的更加丝滑,引出了几个例子。
|
||||
|
||||
**注:完整示例及修复示例已更新至星球。**
|
||||
|
||||
## 死锁
|
||||
|
||||
假设有两个线程互相持有对方的锁,此时我们可以模拟出死锁,例如:
|
||||
|
||||
```cpp
|
||||
void thread_func1() {
|
||||
std::lock_guard<std::mutex> lock1(mutex1);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
std::lock_guard<std::mutex> lock2(mutex2);
|
||||
}
|
||||
|
||||
void thread_func2() {
|
||||
std::lock_guard<std::mutex> lock2(mutex2);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
std::lock_guard<std::mutex> lock1(mutex1);
|
||||
}
|
||||
```
|
||||
|
||||
helgrind使用的方法如下:
|
||||
|
||||
```
|
||||
valgrind --tool=helgrind ./a.out
|
||||
```
|
||||
|
||||
此时我们可以看到死锁的位置,例如这个示例中指出了两个线程在对应位置发生了死锁
|
||||
|
||||
```
|
||||
thread_func2() (deadlock.cc:18)
|
||||
thread_func1() (deadlock.cc:12)
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 数据竞争
|
||||
|
||||
假设有一个共享变量,我们在多线程对它增加10w次,这个结果是多少呢?
|
||||
|
||||
很明显这里产生了多线程竞争全局变量的问题,最终的结果不一致,使用helgrind检测方法同上。
|
||||
|
||||
```cpp
|
||||
int shared_var = 0;
|
||||
|
||||
void increment() {
|
||||
for (int i = 0; i < 100000; ++i) {
|
||||
++shared_var;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
此时,我们可以看到data race的行数是哪一行,然后去解决问题。
|
||||
|
||||

|
||||
|
||||
最后,留几个问题吧:
|
||||
|
||||
1.上面这两个有问题的代码,如何修复?
|
||||
|
||||
2.除了上面工具,还有其他办法?
|
||||
|
||||
> 本节完
|
||||
265
site_extras/cpp-concurrency-libev-event-loop.md
Normal file
265
site_extras/cpp-concurrency-libev-event-loop.md
Normal file
@@ -0,0 +1,265 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/libev-event-loop/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# libev 事件循环原理
|
||||
|
||||
大纲
|
||||
|
||||
[TOC]
|
||||
|
||||
`libev` 是一个跨平台的高效事件通知库,主要用于多路复用事件机制(例如 `select`、`poll`、`epoll` 等)的实现。它的设计目标是提供简单、快速的事件循环机制,特别适合需要高并发和低延迟的场景,如高性能 Web 服务器、网络代理和其他 IO 密集型应用。它的代码量非常少,并且使用在一些生产环境中,非常推荐阅读,本节来讲讲其中的实现原理与使用。
|
||||
|
||||
## 1.基本框架
|
||||
|
||||
libev 的核心是事件循环(event loop),它是应用程序与操作系统之间的接口,用于监听和分发不同类型的事件。libev 的架构非常简洁,主要包含以下几个部分:
|
||||
|
||||
### 1.1 事件句柄(ev_watcher)
|
||||
|
||||
libev 通过事件句柄(watcher)来管理和监听各种事件。每种事件类型(如 IO 事件、定时器事件等)都有一个对应的 watcher 类型。常见的事件句柄包括:
|
||||
|
||||
- **ev_io**:用于监听文件描述符的可读/可写事件。
|
||||
- **ev_timer**:用于定时器事件,支持一次性定时器和重复定时器。
|
||||
- **ev_signal**:用于捕捉信号事件(如 `SIGINT`、`SIGTERM` 等)。
|
||||
|
||||
像上面都可以称之为ev_watcher的子类:
|
||||
|
||||
```cpp
|
||||
typedef struct ev_watcher
|
||||
{
|
||||
int active;
|
||||
int pending;
|
||||
int priority;
|
||||
void *data;
|
||||
void (*cb)(struct ev_loop *loop, struct ev_watcher *w, int revents);
|
||||
} ev_watcher;
|
||||
```
|
||||
|
||||
实际使用时,会涉及到两个关键函数,例如:注册一个可读的标准输入事件
|
||||
|
||||
```cpp
|
||||
ev_io stdin_watcher;
|
||||
ev_io_init(&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
|
||||
ev_io_start(loop, &stdin_watcher);
|
||||
```
|
||||
|
||||
ev_io_init是一个宏,最后展开就是下面代码,主要是对watcher进行初始化,例如:设置callback、fd、events等。
|
||||
|
||||
```cpp
|
||||
do
|
||||
{
|
||||
do
|
||||
{
|
||||
((ev_watcher *)(void *)((&stdin_watcher)))->active = ((ev_watcher *)(void *)((&stdin_watcher)))->pending = 0;
|
||||
((ev_watcher *)(void *)(((&stdin_watcher))))->priority = (0);
|
||||
((((&stdin_watcher)))->cb = ((stdin_cb)), memmove(&((ev_watcher *)(((&stdin_watcher))))->cb, &(((&stdin_watcher)))->cb, sizeof((((&stdin_watcher)))->cb)));
|
||||
} while (0);
|
||||
do
|
||||
{
|
||||
((&stdin_watcher))->fd = ((0));
|
||||
((&stdin_watcher))->events = ((EV_READ)) | EV__IOFDSET;
|
||||
} while (0);
|
||||
} while (0);
|
||||
```
|
||||
|
||||
ev_io_start主要是修改anfs与fdchanges数组。
|
||||
|
||||
- 对于已经active的watcher直接返回
|
||||
- 如果还不活跃,则设置active与priority
|
||||
- 使用头插法插入到anfds对应fd的链表中,并将当前watcher设置为head
|
||||
|
||||
```cpp
|
||||
wlist_add(&((loop)->anfds)[fd].head, (WL)w);
|
||||
|
||||
static __inline__ void
|
||||
wlist_add(WL *head, WL elem)
|
||||
{
|
||||
elem->next = *head;
|
||||
*head = elem;
|
||||
}
|
||||
```
|
||||
|
||||
- 将fd插入到fdchanges数组末尾
|
||||
|
||||
```cpp
|
||||
++((loop)->fdchangecnt);
|
||||
((loop)->fdchanges)[((loop)->fdchangecnt) - 1] = fd;
|
||||
```
|
||||
|
||||
- 设置标记
|
||||
|
||||
```cpp
|
||||
w->events &= ~EV__IOFDSET;
|
||||
```
|
||||
|
||||
### 1.2 IO多路复用
|
||||
|
||||
在libev中支持epoll、poll、select等,其中在loop中有2个回调函数:
|
||||
|
||||
```cpp
|
||||
void (*backend_modify)(struct ev_loop *loop, int fd, int oev, int nev);
|
||||
void (*backend_poll)(struct ev_loop *loop, ev_tstamp timeout);
|
||||
```
|
||||
|
||||
我们以epool为例,backend_modify就是epoll_modify,backend_poll就是epoll_poll。
|
||||
|
||||
epoll_modify就是大家通常使用的epoll_ctl,当事件发生变化使用EPOLL_CTL_MOD,否则使用EPOLL_CTL_ADD。
|
||||
|
||||
```cpp
|
||||
epoll_ctl (backend_fd, oev && oldmask != nev ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &ev)
|
||||
```
|
||||
|
||||
epoll_poll执行逻辑如下:
|
||||
|
||||
- epoll_wait获取就绪事件列表(loop->epoll_events)
|
||||
- 对于就绪事件,执行fd_event放入loop的pendings对应优先级的数组中。
|
||||
|
||||
```cpp
|
||||
static __inline__ void
|
||||
fd_event(struct ev_loop *loop, int fd, int revents)
|
||||
{
|
||||
ANFD *anfd = ((loop)->anfds) + fd;
|
||||
if (__builtin_expect((!!(!anfd->reify)), (1)))
|
||||
fd_event_nocheck(loop, fd, revents);
|
||||
}
|
||||
|
||||
static __inline__ void
|
||||
fd_event_nocheck(struct ev_loop *loop, int fd, int revents)
|
||||
{
|
||||
ANFD *anfd = ((loop)->anfds) + fd;
|
||||
ev_io *w;
|
||||
for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
|
||||
{
|
||||
int ev = w->events & revents;
|
||||
if (ev)
|
||||
ev_feed_event(loop, (W)w, ev);
|
||||
}
|
||||
}
|
||||
|
||||
// 省略部分代码
|
||||
void __attribute__((__noinline__))
|
||||
ev_feed_event(struct ev_loop *loop, void *w, int revents)
|
||||
{
|
||||
w_->pending = ++((loop)->pendingcnt)[pri];
|
||||
((loop)->pendings)[pri][w_->pending - 1].w = w_;
|
||||
((loop)->pendings)[pri][w_->pending - 1].events = revents;
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 Timer
|
||||
|
||||
Timer内部实现采用了二叉堆与四叉堆,这里之所用四叉堆,是因为四叉堆的缓存效率更高,其实现如下:
|
||||
|
||||
```cpp
|
||||
#define DHEAP 4
|
||||
#define HEAP0 (DHEAP - 1) /* index of first element in heap */
|
||||
#define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0)
|
||||
#define UPHEAP_DONE(p,k) ((p) == (k))
|
||||
```
|
||||
|
||||
注意上面使用了HEAP0作为第一个元素,即offset,堆内部的实现便是upheap、downheap,比较简单就不赘述。其结构为:
|
||||
|
||||
```cpp
|
||||
typedef ev_watcher_time *WT;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
ev_tstamp at;
|
||||
WT w;
|
||||
} ANHE;
|
||||
```
|
||||
|
||||
heap的排序是按照at来比较,at为定时器到期时间,堆排序则按照at的值由小到大排序。
|
||||
|
||||
### 1.4 事件循环(ev_loop)
|
||||
|
||||
通常使用如下:
|
||||
|
||||
```cpp
|
||||
struct ev_loop *loop = EV_DEFAULT;
|
||||
ev_run(loop, 0);
|
||||
```
|
||||
|
||||
EV_DEFAULT会调用ev_default_loop函数,初始化一个ev_loop结构,里面主要是通过loop_init初始化loop结构,比如:选择epoll还是poll、select。
|
||||
|
||||
最核心的点:epoll_init发生在上面loop创建时。
|
||||
|
||||
ev_run比较复杂,主要做几件事:
|
||||
|
||||
- fd_reify
|
||||
|
||||
遍历前面提到的fdchanges数组,根据fd从anfds中取出链表,遍历所有事件链表,得到所有事件,判断当前最新的事件与之前老的事件(events)是否一致,不一致调用epoll_modify(或者第一次添加事件)。
|
||||
|
||||
```cpp
|
||||
typedef struct
|
||||
{
|
||||
WL head; // 事件链表
|
||||
unsigned char events; // 前面事件
|
||||
// other
|
||||
} ANFD;
|
||||
```
|
||||
|
||||
- backend_poll
|
||||
|
||||
见前面backend_poll的实现,会获取就绪事件并把事件放入pendings数组里面,即放到对应的优先级队列的最后。
|
||||
|
||||
- timer_reify,事件未过期不做处理,过期了执行下面逻辑:
|
||||
|
||||
- 没有设置repeat的timer
|
||||
- 调用ev_timer_stop清除
|
||||
|
||||
- 设置repeat的timer
|
||||
|
||||
例如:`ev_timer_init(&timer_watcher, timer_cb, 2.0, 3.0);``
|
||||
|
||||
``ev_timer` 的 `at` 设置为当前时间加上 2 秒(即定时器将在 2 秒后触发),并且 `repeat` 设置为 3 秒,那么定时器将首先在 2 秒后触发,然后每隔 3 秒触发一次。
|
||||
|
||||
```cpp
|
||||
if (w->repeat)
|
||||
{
|
||||
// 更新下次触发时间
|
||||
((WT)(w))->at += w->repeat;
|
||||
// 过期了
|
||||
if (((WT)(w))->at < ((loop)->mn_now))
|
||||
((WT)(w))->at = ((loop)->mn_now); // 设置当前时间
|
||||
// 设置堆顶元素为前面w->at
|
||||
(((loop)->timers)[HEAP0]).at = (((loop)->timers)[HEAP0]).w->at;
|
||||
// 调整堆
|
||||
downheap(((loop)->timers), ((loop)->timercnt), HEAP0);
|
||||
}
|
||||
```
|
||||
|
||||
- Invoke_cb
|
||||
|
||||
Invoke_cb默认是ev_invoke_pending,从对应优先队列中取出事件,调用callback函数进行事件处理。
|
||||
|
||||
```cpp
|
||||
ANPENDING *p = ((loop)->pendings)[((loop)->pendingpri)] + --((loop)->pendingcnt)[((loop)->pendingpri)];
|
||||
(p->w)->cb(loop, (p->w), (p->events));
|
||||
```
|
||||
|
||||
## 2.如何使用?
|
||||
|
||||
```cpp
|
||||
git clone git@github.com:enki/libev.git
|
||||
./configure
|
||||
make && make install
|
||||
```
|
||||
|
||||
项目编译:
|
||||
|
||||
```
|
||||
gcc main.c -lev
|
||||
```
|
||||
|
||||
## 3.课后作业
|
||||
|
||||
最后,留一个课后题目,你是否可以使用libev写一个这样的例子?
|
||||
|
||||
当我们输入数据的时候,stdio事件返回ready,如果输入超时,则返回timeout,演示效果:
|
||||
|
||||
```cpp
|
||||
[light@i-7dwsk0ty libev]$ ./a.out
|
||||
timeout
|
||||
[light@i-7dwsk0ty libev]$ ./a.out
|
||||
21
|
||||
stdin ready
|
||||
```
|
||||
156
site_extras/cpp-concurrency-std-thread-internals.md
Normal file
156
site_extras/cpp-concurrency-std-thread-internals.md
Normal file
@@ -0,0 +1,156 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/std-thread-internals/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ std::thread 内核实现
|
||||
|
||||
## 深度揭秘std::thread
|
||||
|
||||
当我们在写一个lambda时,传给thread,线程创建与task调用是在何时触发?
|
||||
|
||||
```cpp
|
||||
auto t = std::thread([this] {
|
||||
// do something
|
||||
});
|
||||
```
|
||||
|
||||
这这个线程中传递了一个lambda,那么本节所要解决的问题是:这个lambda何时触发?是在构造的时候?还是在某处调用时?
|
||||
|
||||
来,让我们一起进入源码时代。
|
||||
|
||||
## 1._M_make_routine
|
||||
|
||||
本节所分析的代码分别如下:
|
||||
|
||||
1) 头文件
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libstdc%2B%2B-v3/include/std/thread
|
||||
|
||||
2. 实现文件
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libstdc%2B%2B-v3/src/c%2B%2B11/thread.cc
|
||||
|
||||
3. posix头文件
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libgcc/gthr-posix.h
|
||||
|
||||
上面的代码会调用下面这个构造函数:
|
||||
|
||||
```cpp
|
||||
template<typename _Callable, typename... _Args>
|
||||
explicit
|
||||
thread(_Callable&& __f, _Args&&... __args)
|
||||
{
|
||||
_M_start_thread(_M_make_routine(std::__bind_simple(
|
||||
std::forward<_Callable>(__f),
|
||||
std::forward<_Args>(__args)...)));
|
||||
}
|
||||
```
|
||||
|
||||
`__f`为我们传入的lambda,这里通过bind将lambda与参数绑定在一起,随后传给`_M_make_routine`,便构造出`_Impl`。
|
||||
|
||||
```cpp
|
||||
template<typename _Callable>
|
||||
shared_ptr<_Impl<_Callable>>
|
||||
_M_make_routine(_Callable&& __f)
|
||||
{
|
||||
// Create and allocate full data structure, not base.
|
||||
return std::make_shared<_Impl<_Callable>>(std::forward<_Callable>(__f));
|
||||
}
|
||||
```
|
||||
|
||||
而`_Impl`里面存的是刚才bind的返回结果`_M_func`。
|
||||
|
||||
```cpp
|
||||
template<typename _Callable>
|
||||
struct _Impl : public _Impl_base
|
||||
{
|
||||
_Callable _M_func;
|
||||
|
||||
_Impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
|
||||
{ }
|
||||
|
||||
void
|
||||
_M_run() { _M_func(); }
|
||||
};
|
||||
```
|
||||
|
||||
随后`_M_make_routine`创建好的`shared_ptr<_Impl<_Callable>>`传递给`_M_start_thread`。
|
||||
|
||||
## 2._M_start_thread
|
||||
|
||||
`_M_start_thread`会调用`__gthread_create`,在这里会传递`execute_native_thread_routine`。
|
||||
|
||||
```cpp
|
||||
void
|
||||
thread::_M_start_thread(__shared_base_type __b)
|
||||
{
|
||||
if (!__gthread_active_p())
|
||||
#if __EXCEPTIONS
|
||||
throw system_error(make_error_code(errc::operation_not_permitted),
|
||||
"Enable multithreading to use std::thread");
|
||||
#else
|
||||
__throw_system_error(int(errc::operation_not_permitted));
|
||||
#endif
|
||||
|
||||
__b->_M_this_ptr = __b;
|
||||
int __e = __gthread_create(&_M_id._M_thread,
|
||||
&execute_native_thread_routine, __b.get());
|
||||
if (__e)
|
||||
{
|
||||
__b->_M_this_ptr.reset();
|
||||
__throw_system_error(__e);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
关键点1:`execute_native_thread_routine`
|
||||
|
||||
在下面代码中给出了几个信息:
|
||||
|
||||
第一:为何要extern "C"
|
||||
|
||||
第二:调用了`_M_run()`
|
||||
|
||||
```cpp
|
||||
extern "C"
|
||||
{
|
||||
static void*
|
||||
execute_native_thread_routine(void* __p)
|
||||
{
|
||||
thread::_Impl_base* __t = static_cast<thread::_Impl_base*>(__p);
|
||||
thread::__shared_base_type __local;
|
||||
__local.swap(__t->_M_this_ptr);
|
||||
|
||||
__try
|
||||
{
|
||||
__t->_M_run();
|
||||
}
|
||||
__catch(const __cxxabiv1::__forced_unwind&)
|
||||
{
|
||||
__throw_exception_again;
|
||||
}
|
||||
__catch(...)
|
||||
{
|
||||
std::terminate();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
} // extern "C"
|
||||
```
|
||||
|
||||
关键点2:`__gthread_create`
|
||||
|
||||
调用了pthread_create
|
||||
|
||||
```cpp
|
||||
static inline int
|
||||
__gthread_create (__gthread_t *__threadid, void *(*__func) (void*),
|
||||
void *__args)
|
||||
{
|
||||
return __gthrw_(pthread_create) (__threadid, NULL, __func, __args);
|
||||
}
|
||||
```
|
||||
|
||||
好了,我们来梳理一下上面的流程,当我们构造std::thread时,传入了自定义的callback(lambda)执行我们的业务逻辑,std::thread构造函数会发起pthread_create的调用,同时把execute_native_thread_routine以C语言风格传递给pthread_create,在执行pthread_create会执行execute_native_thread_routine,那么里面的`_M_run()`便会执行,这便是对应我们的lambda函数调用。
|
||||
|
||||
本节对线程的调用有了更近一步的认识,你学到了吗,欢迎分享。
|
||||
742
site_extras/cpp-concurrency-std-thread-jthread-guide.md
Normal file
742
site_extras/cpp-concurrency-std-thread-jthread-guide.md
Normal file
@@ -0,0 +1,742 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-concurrency/std-thread-jthread-guide/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ std::thread 与 jthread
|
||||
|
||||
## 全面解析thread 与 jthread
|
||||
|
||||
## 1.准备工作
|
||||
|
||||
本文的内容基于gcc-13的源码进行展开,讲详细讲解C++11 std::thread的使用与内核实现、讲解如何使用pthread + thread混用,讲解C++20 jthread的用法与内核实现。
|
||||
|
||||
如果说你是一个多线程开发的小白/大神,本篇文章都非常的适合学习,既会包含基础的理论知识,还会包含丰富的实践与内核代码揭秘。
|
||||
|
||||
源码剖析版本:gcc-13
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/tree/releases/gcc-13
|
||||
|
||||
大纲如下:
|
||||
|
||||
[TOC]
|
||||
|
||||
## 2.C++11的thread
|
||||
|
||||
### 2.1 基本使用
|
||||
|
||||
创建一个thread,然后传入自己的执行函数,参数等。
|
||||
|
||||
这里的result可以使用atomic 也可以使用promise。
|
||||
|
||||
基本使用中一般需要注意t.join,让主线程等待子线程,它会阻塞当前线程,直到调用 join() 的线程执行完成。
|
||||
|
||||
```cpp
|
||||
std::atomic<int> result(0);
|
||||
|
||||
void threadFunction(int a, int b) {
|
||||
result = a + b;
|
||||
std::cout << "Child thread finished its work.\n";
|
||||
}
|
||||
|
||||
int main() {
|
||||
int a = 5;
|
||||
int b = 7;
|
||||
|
||||
std::thread t(threadFunction, a, b);
|
||||
|
||||
t.join();
|
||||
std::cout << "Result computed by the child thread: " << result << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
如果你没有在线程上指定 join() 或 dettach() ,则会导致运行时错误,因为主/当前线程将完成其执行,而创建的其他线程仍将运行。
|
||||
|
||||
示例:去掉上面的t.join(),你的程序将会崩溃。
|
||||
|
||||
```
|
||||
Result computed by the child thread: 0
|
||||
Child thread finished its work.
|
||||
terminate called without an active exception
|
||||
[1] 52814 abort ./a.out
|
||||
```
|
||||
|
||||
### 2.2 STL实现
|
||||
|
||||
大家可以去看std_thread.h文件,来跟我一起阅读内核实现。
|
||||
|
||||
代码路径:gcc/libstdc++-v3/include/bits/std_thread.h
|
||||
|
||||
#### 2.2.1 与pthread关联
|
||||
|
||||
首先它是一个类thread,然后有一个比较重要的类型,像我的Linux系统上面这个宏是打开的,默认一般是`__gthread_t`,而这个通常是一个pthread_t。
|
||||
|
||||
```cpp
|
||||
#ifdef _GLIBCXX_HAS_GTHREADS
|
||||
using native_handle_type = __gthread_t;
|
||||
#else
|
||||
using native_handle_type = int;
|
||||
#endif
|
||||
```
|
||||
|
||||
即:
|
||||
|
||||
```
|
||||
typedef pthread_t __gthread_t;
|
||||
```
|
||||
|
||||
所以我们可以得到第一个结论:底层实现基于linux的pthread实现。
|
||||
|
||||
#### 2.2.2 内部id
|
||||
|
||||
thread类,有一个私有成员叫做`_M_id`。
|
||||
|
||||
```cpp
|
||||
private:
|
||||
id _M_id;
|
||||
```
|
||||
|
||||
其类型是哪部的一个类,再往里面深入就是native_handle_type。
|
||||
|
||||
```cpp
|
||||
class id
|
||||
{
|
||||
native_handle_type _M_thread;
|
||||
|
||||
public:
|
||||
id() noexcept : _M_thread() { }
|
||||
|
||||
explicit
|
||||
id(native_handle_type __id) : _M_thread(__id) { }
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
那再结合上面的内容,可以得到:
|
||||
|
||||
```cpp
|
||||
private:
|
||||
pthread_t _M_id;
|
||||
```
|
||||
|
||||
是不是很熟悉,我们得到了第二个知识点:thread内部维护了一个id,在linux上默认是pthread_t。
|
||||
|
||||
#### 2.2.3 是否可连接
|
||||
|
||||
如果一个线程处于 "joinable" 状态,那么在它执行完成之前,程序可以调用 `join()` 函数来等待该线程的执行完成。
|
||||
|
||||
joinable判断依据是:
|
||||
|
||||
```cpp
|
||||
_M_id != id()
|
||||
```
|
||||
|
||||
基于前面的内容,我们可以推导出:
|
||||
|
||||
```cpp
|
||||
pthread_t _M_id;
|
||||
pthread_t null_thread = pthread_t();
|
||||
_M_id != null_thread;
|
||||
```
|
||||
|
||||
即:joinable判断依据是当前线程是否不等于默认的线程id(0)。
|
||||
|
||||
join方法非常的重要,我们通常需要使用它,那它的实现原理简单来说就是如下:
|
||||
|
||||
- 是否可joinable
|
||||
- 是,调用pthread_join(这里的gthread实际上会调用到pthread的接口)
|
||||
- 否或者上面join有错误,跑出异常EINVAL或者join错误。
|
||||
- 设置为不可joinable,即:设置内部的线程id为0
|
||||
|
||||
```cpp
|
||||
thread::join()
|
||||
{
|
||||
int __e = EINVAL;
|
||||
|
||||
if (_M_id != id()) // 是否可joinable
|
||||
__e = __gthread_join(_M_id._M_thread, 0);
|
||||
|
||||
if (__e)
|
||||
__throw_system_error(__e);
|
||||
|
||||
_M_id = id(); // _M_id = pthread_t(),设置为0
|
||||
}
|
||||
```
|
||||
|
||||
在join之后,如果我们再join,此时便会抛出上面EINVAL异常,即:无效参数。
|
||||
|
||||
```
|
||||
terminate called after throwing an instance of 'std::system_error'
|
||||
what(): Invalid argument
|
||||
```
|
||||
|
||||
#### 2.2.4 分离
|
||||
|
||||
跟join类似,不过相反,告诉程序你不再关心该线程的执行了,实现逻辑除了调用接口不一样,其他地方都一致,不赘述了。
|
||||
|
||||
detach重使用的是pthread_detach。
|
||||
|
||||
```cpp
|
||||
void
|
||||
thread::detach()
|
||||
{
|
||||
int __e = EINVAL;
|
||||
|
||||
if (_M_id != id())
|
||||
__e = __gthread_detach(_M_id._M_thread);
|
||||
|
||||
if (__e)
|
||||
__throw_system_error(__e);
|
||||
|
||||
_M_id = id();
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2.5 构造与析构
|
||||
|
||||
##### 2.2.5.1 构造
|
||||
|
||||
使用:
|
||||
|
||||
```
|
||||
thread t1;
|
||||
```
|
||||
|
||||
默认构造内核代码:
|
||||
|
||||
```cpp
|
||||
thread() noexcept = default;
|
||||
```
|
||||
|
||||
带参数的构造使用:
|
||||
|
||||
```cpp
|
||||
std::thread t2(threadFunction, a, b);
|
||||
```
|
||||
|
||||
带参数构造内核代码:
|
||||
|
||||
```cpp
|
||||
template <typename _Callable, typename... _Args,
|
||||
typename = _Require<__not_same<_Callable>>>
|
||||
explicit thread(_Callable &&__f, _Args &&...__args) {}
|
||||
```
|
||||
|
||||
内部实现是:
|
||||
|
||||
```cpp
|
||||
_M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
|
||||
std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
|
||||
_M_thread_deps_never_run);
|
||||
```
|
||||
|
||||
可以看到核心函数是`_M_start_thread`,这里面的代码简化为:
|
||||
|
||||
```cpp
|
||||
const int err = __gthread_create(&_M_id._M_thread,
|
||||
&execute_native_thread_routine,
|
||||
state.get());
|
||||
if (err)
|
||||
__throw_system_error(err);
|
||||
```
|
||||
|
||||
而`__gthread_create`可以理解为是pthread_create,那么是不是非常的清楚了?
|
||||
|
||||
注意到这里有一个细节就是传递给pthread_create的参数重func是execute_native_thread_routine,上面转化为pthread_create为:
|
||||
|
||||
```cpp
|
||||
pthread_create (&_M_id._M_thread, NULL, &execute_native_thread_routine, state.get());
|
||||
```
|
||||
|
||||
而execute_native_thread_routine是一个extern "C" 包裹的函数,使 C++ 中的函数名称具有 C 链接。
|
||||
|
||||
所以上面构造函数逻辑非常清晰了,就是调用pthread_create初始化内部线程id,那么这里有一个疑问,**用户传递的函数与参数怎么处理呢?**
|
||||
|
||||
这就引入了State,细心的朋友注意到上面pthread_create的最后一个参数是通常的函数参数:`state.get()`,函数是execute_native_thread_routine。
|
||||
|
||||
```cpp
|
||||
static void*
|
||||
execute_native_thread_routine(void* __p)
|
||||
{
|
||||
thread::_State_ptr __t{ static_cast<thread::_State*>(__p) };
|
||||
__t->_M_run();
|
||||
return nullptr;
|
||||
}
|
||||
```
|
||||
|
||||
`_State`是一个接口,其实现是`_State_impl`,可以看到参数与函数是转发到了这里面,然后通过`_M_run`去执行用户传递的函数,执行的时候是调用`_Callable`的operator(),在前面我们知道创建的时候是带了`_Wrapper`,所以`_Callable`等于`_Wrapper`,而`__Wrapper`又是一个`_Call_wrapper`别名,会将用户的函数与参数传递进去。
|
||||
|
||||
```cpp
|
||||
using _Wrapper = _Call_wrapper<_Callable, _Args...>;
|
||||
|
||||
struct _State
|
||||
{
|
||||
virtual ~_State();
|
||||
virtual void _M_run() = 0;
|
||||
};
|
||||
using _State_ptr = unique_ptr<_State>;
|
||||
|
||||
|
||||
template <typename _Callable>
|
||||
struct _State_impl : public _State
|
||||
{
|
||||
_Callable _M_func;
|
||||
|
||||
template <typename... _Args>
|
||||
_State_impl(_Args &&...__args)
|
||||
: _M_func(std::forward<_Args>(__args)...)
|
||||
{
|
||||
}
|
||||
|
||||
void
|
||||
_M_run() { _M_func(); }
|
||||
};
|
||||
```
|
||||
|
||||
所以到这里,我们可以看一下
|
||||
|
||||
```cpp
|
||||
template <typename... _Tp>
|
||||
using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
|
||||
```
|
||||
|
||||
相当于将上面_Call_wrapper的所有参数去掉引用和修饰之后作为tuple传递进去,即:
|
||||
|
||||
```cpp
|
||||
_Invoker<tuple<_Callable, Arg1, Arg2, ...>
|
||||
```
|
||||
|
||||
然后最终传递给`std::__invoke`。
|
||||
|
||||
所以,假设我写了这么一行代码:
|
||||
|
||||
```cpp
|
||||
_Call_wrapper<decltype(&add), int, int> invoker(&add, 3, 4);
|
||||
```
|
||||
|
||||
它会通过invoke帮你调用add函数。
|
||||
|
||||
```cpp
|
||||
invoke(_Fn&& __f, _Args&&... __args)
|
||||
```
|
||||
|
||||
当然上面调用的是其内部的`__invoke`,两者没有什么区别,一个是对外的接口,一个是对内的。
|
||||
|
||||
经过上面的讲解,我们可以小结一下:
|
||||
|
||||
- 带参数的构造函数会创建tid,通过pthread_create
|
||||
- 传递给pthread_create的函数是一个包裹的函数,内部使用State去驱动
|
||||
- 用户通过将函数、参数传递给thread,最终调用这个函数是通过`std::__invoke`来驱动起来。
|
||||
|
||||
##### 2.2.5.2 拷贝与移动
|
||||
|
||||
thead禁止了拷贝构造、拷贝赋值,只支持移动构造与移动赋值。
|
||||
|
||||
```cpp
|
||||
thread(const thread &) = delete;
|
||||
thread &operator=(const thread &) = delete;
|
||||
```
|
||||
|
||||
移动构造
|
||||
|
||||
```cpp
|
||||
thread(thread &&__t) noexcept
|
||||
{
|
||||
swap(__t);
|
||||
}
|
||||
|
||||
void
|
||||
swap(thread &__t) noexcept
|
||||
{
|
||||
std::swap(_M_id, __t._M_id);
|
||||
}
|
||||
```
|
||||
|
||||
移动赋值
|
||||
|
||||
```cpp
|
||||
thread &operator=(thread &&__t) noexcept
|
||||
{
|
||||
if (joinable())
|
||||
std::__terminate();
|
||||
swap(__t);
|
||||
return *this;
|
||||
}
|
||||
```
|
||||
|
||||
##### 2.2.5.3 析构
|
||||
|
||||
析构的原则是你创建的线程资源得消费/释放掉,而一个线程如果是可joinable,那么它被pthread_create了,但是还没有被使用,此时会直接terminate。
|
||||
|
||||
```cpp
|
||||
~thread()
|
||||
{
|
||||
if (joinable())
|
||||
std::__terminate();
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2.6 其他成员
|
||||
|
||||
例如:获取线程内部的线程id、线程的id内部的`_M_thread`。
|
||||
|
||||
```cpp
|
||||
id
|
||||
get_id() const noexcept
|
||||
{ return _M_id; }
|
||||
|
||||
native_handle_type
|
||||
native_handle()
|
||||
{ return _M_id._M_thread; }
|
||||
```
|
||||
|
||||
#### 2.2.7 面试考点
|
||||
|
||||
**1.构造与析构**
|
||||
|
||||
所以这里有一个提问:下面代码有什么问题吗?
|
||||
|
||||
```cpp
|
||||
// test1.cc
|
||||
int main() {
|
||||
thread t1;
|
||||
}
|
||||
|
||||
// test2.cc
|
||||
int main() {
|
||||
std::thread t2(threadFunction, a, b);
|
||||
}
|
||||
```
|
||||
|
||||
其答案是:test1正常运行,test2 crash!
|
||||
|
||||
原因是:thread的默认构造函数不做任何事情,而带参数的构造函数里面会调用`__gthread_create`(即:pthread_create)创建线程,即初始化了内部的`_M_id._M_thread`,在析构的时候会判断joinable,此时的`_M_id`与id()是不相等的,即:joinable = true,直接std::__terminate()此时crash了。
|
||||
|
||||
**2.移动赋值**
|
||||
|
||||
假设现在有下面两个函数f1、f2,这两个函数可以正常运行吗?为什么?
|
||||
|
||||
```cpp
|
||||
void f1() {
|
||||
std::thread t1(tfunc);
|
||||
std::thread t2;
|
||||
t2 = std::move(t1);
|
||||
t2.join();
|
||||
}
|
||||
void f2() {
|
||||
std::thread t1(tfunc);
|
||||
std::thread t2(tfunc);
|
||||
t2 = std::move(t1);
|
||||
t2.join();
|
||||
}
|
||||
```
|
||||
|
||||
其答案是:f1正常运行,f2 crash!
|
||||
|
||||
原因是:`f1`中t2使用了默认构造函数(不做任何事情),所以`t2`本身是非joinable的,可以安全使用移动赋值。但是,`f2`的t2是可joinable的(因此构造函数中初始化了tid),而移动赋值时会判断是否joinable,如果joinable,那么直接terminate,这其实比较好理解,因为t2本身的线程被创建了,还没有消费使用,就给swap出去了,那如何修复这个问题呢?
|
||||
|
||||
其实很简单:在前面加个join即可:
|
||||
|
||||
```cpp
|
||||
t2.join(); // 新加的
|
||||
t2 = std::move(t1);
|
||||
t2.join();
|
||||
```
|
||||
|
||||
可能有些人觉得t2搞了两次join难道没问题吗,因此此时第二次的t2实际上已经是t1了,所以可以看作是:
|
||||
|
||||
```cpp
|
||||
t2.join();
|
||||
t1.join();
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 3.C++20的jthread
|
||||
|
||||
自C++20之后引入了`std::jthread`,它可以自动join启动的线程,并发出中断信号。
|
||||
|
||||
### 3.1 基本使用
|
||||
|
||||
如果我们使用前面的thread,下出下面这个代码会core掉,因为在析构函数中会去判断是否joinable,此时会terminate。
|
||||
|
||||
```cpp
|
||||
std::thread t{ [] {std::cout << "hello std::thread" << std::endl; } };
|
||||
|
||||
std::cout << "t.joinable(): " << t.joinable() << std::endl;
|
||||
```
|
||||
|
||||
如果使用了C++20的jthread,便不会有这个问题,例如:
|
||||
|
||||
```cpp
|
||||
std::jthread tj{ [] {std::cout << "hello std::jthread" << std::endl; } };
|
||||
|
||||
std::cout << "tj.joinable(): " << tj.joinable() << std::endl;
|
||||
```
|
||||
|
||||
此时你会发现可以正常运行!
|
||||
|
||||
### 3.2 STL实现
|
||||
|
||||
jthread是在thread里面,其实现基于前面的thread,源码位置:gcc/libstdc++-v3/include/std/thread
|
||||
|
||||
到底有什么秘密呢?我们一起来揭秘。
|
||||
|
||||
#### 3.2.1 与thread关联
|
||||
|
||||
jthread与thread息息相关,可以说基于thread实现,其中最核心的成员就是thread类型,而内部的id与native_handle_type类型均使用了thread内部的。
|
||||
|
||||
```cpp
|
||||
using id = thread::id;
|
||||
using native_handle_type = thread::native_handle_type;
|
||||
|
||||
thread _M_thread;
|
||||
```
|
||||
|
||||
#### 3.2.2 stop_token与stop_source
|
||||
|
||||
jthread内部使用了 std::stop_token 增强控制。std::stop_token 是一种向线程执行发送停止请求的机制。 它作为请求运行,如果在线程执行中正确处理,则允许其被终止。
|
||||
|
||||
内部使用了std::stop_source成员来维护。
|
||||
|
||||
```cpp
|
||||
stop_source _M_stop_source;
|
||||
```
|
||||
|
||||
下面我们一起来看看STL的实现。
|
||||
|
||||
**1.stop_source**
|
||||
|
||||
首先stop_source内部会维护一个state,叫做:
|
||||
|
||||
```cpp
|
||||
stop_token::_Stop_state_ref _M_state;
|
||||
```
|
||||
|
||||
这个里面便是:
|
||||
|
||||
```
|
||||
_Stop_state_t* _M_ptr
|
||||
```
|
||||
|
||||
因为一个stop_source可以被不同的线程所持有,所以它可以是共享的,因此内部是通过一个引用来做的,所以你可能会在源码里面看到`_Stop_state_ref`,它来负责管理整个state的生命周期,所有权问题。其共享的实现是通过底层的`_Stop_state_t`实现,内部有两个成员非常重要:
|
||||
|
||||
```cpp
|
||||
using value_type = uint32_t;
|
||||
std::atomic<value_type> _M_owners{1};
|
||||
std::atomic<value_type> _M_value{_S_ssrc_counter_inc};
|
||||
```
|
||||
|
||||
一个是`_M_owners`,管理所有权的;`_M_value`负责管理什么时候停止。
|
||||
|
||||
我们平时用的三个接口分别是:
|
||||
|
||||
- stop_possible
|
||||
- stop_requested
|
||||
- request_stop
|
||||
|
||||
底层便会给`_M_value`设置上对应的bit
|
||||
|
||||
```cpp
|
||||
static constexpr value_type _S_stop_requested_bit = 1;
|
||||
static constexpr value_type _S_locked_bit = 2;
|
||||
static constexpr value_type _S_ssrc_counter_inc = 4;
|
||||
```
|
||||
|
||||
当用户请求停止:request_stop,此时会设置上`_S_stop_requested_bit`,如果用户调用了stop_requested,那么也是去查看内部的`_M_value`是否设置上`_S_stop_requested_bit`。
|
||||
|
||||
`_S_locked_bit`与stop_possible接口有关,如果已经发出了停止请求或者仍然存在可以发出停止请求,那么stop_possible会返回true。
|
||||
|
||||
另外一个是`_S_ssrc_counter_inc`,这个是默认值,在stop_source的构造/拷贝构造时会给value加上`_S_ssrc_counter_inc`。
|
||||
|
||||
**2.stop_token**
|
||||
|
||||
像上面讲到的`_Stop_state_ref`所有内容基本都在stop_token里面,它的内部也是维护了一个state,叫做:
|
||||
|
||||
```
|
||||
_Stop_state_ref _M_state;
|
||||
```
|
||||
|
||||
实现细节与上面一致,就不赘述了。那么它与stop_source的区别是什么呢?
|
||||
|
||||
这里引用cppreference的解释:stop_token 类提供了检查是否已为其关联的 std::stop_source 对象发出或可以发出停止请求的方法。 它本质上是相关停止状态的线程安全“视图”。
|
||||
|
||||
> https://en.cppreference.com/w/cpp/thread/stop_token
|
||||
|
||||
**3.stop_callback**
|
||||
|
||||
stop_callback与stop_token的关系是stop_callback会注册到stop_token里面,stop_token内部会维持一个双向链表结构来对callback进行删除与新增,插入callback采用的是头插法。
|
||||
|
||||
callback触发时机有两块:
|
||||
|
||||
- 在request_stop时触发
|
||||
|
||||
callback提前注册到stop_token里面,那么在执行一段时间,用户发起请求,此时会触发callback。
|
||||
|
||||
```cpp
|
||||
auto onStop = []() {
|
||||
std::cout << "Timer has stopped." << std::endl;
|
||||
};
|
||||
|
||||
// Register the onStop callback with stop_callback
|
||||
std::stop_callback callback(source.get_token(), onStop);
|
||||
// do something for example: sleep
|
||||
|
||||
// stop
|
||||
source.request_stop(); // invoke callback
|
||||
```
|
||||
|
||||
- 注册时立即触发
|
||||
|
||||
stop_token已经要求停止,此时callback在注册时会立即触发,因为线程已经执行完了,此时应该执行回调。
|
||||
|
||||
```cpp
|
||||
thread.request_stop();
|
||||
std::stop_callback callback(stopToken, []() {
|
||||
std::cout << "Callback executed" << std::endl;
|
||||
}); // invoke callback
|
||||
```
|
||||
|
||||
具体STL中的实现是`_M_register_callback`会调用`__cb->_M_run()`,此时会调用callback函数。
|
||||
|
||||
#### 3.2.3 构造与析构
|
||||
|
||||
##### 3.2.3.1 构造
|
||||
|
||||
- 默认构造
|
||||
|
||||
默认构造会初始化一个空的stopstate,内部tid不做维护,行为跟thread一致。
|
||||
|
||||
```cpp
|
||||
jthread() noexcept
|
||||
: _M_stop_source{nostopstate}
|
||||
{ }
|
||||
```
|
||||
|
||||
- 带参数构造
|
||||
|
||||
初始化`_M_thread`,它是通过`_S_create`然后调用`_S_create_pmf`创建一个thread,然后给`_M_thread`,这样内部的thread变被构造好了。
|
||||
|
||||
```cpp
|
||||
template<typename _Callable, typename... _Args,
|
||||
typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
|
||||
jthread>>>
|
||||
explicit
|
||||
jthread(_Callable&& __f, _Args&&... __args)
|
||||
: _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
|
||||
std::forward<_Args>(__args)...)}
|
||||
{ }
|
||||
```
|
||||
|
||||
##### 3.2.3.2 拷贝与移动
|
||||
|
||||
拷贝构造与拷贝赋值被禁用掉了,行为跟thread一致!
|
||||
|
||||
```
|
||||
jthread(const jthread&) = delete;
|
||||
jthread& operator=(const jthread&) = delete;
|
||||
```
|
||||
|
||||
移动构造默认,移动赋值使用swap。
|
||||
|
||||
```cpp
|
||||
jthread(jthread&&) noexcept = default;
|
||||
|
||||
jthread&
|
||||
operator=(jthread&& __other) noexcept
|
||||
{
|
||||
std::jthread(std::move(__other)).swap(*this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void
|
||||
swap(jthread& __other) noexcept
|
||||
{
|
||||
std::swap(_M_stop_source, __other._M_stop_source);
|
||||
std::swap(_M_thread, __other._M_thread);
|
||||
}
|
||||
```
|
||||
|
||||
##### 3.2.3.3 析构
|
||||
|
||||
析构决定了jthread在一开始的行为,为何我们不用手动join,是因为在析构的时候,它会去判断是否可join,如果joinable,那么用户没有join过,析构函数帮你调用一下join,同时会在之前检查request_stop。
|
||||
|
||||
```cpp
|
||||
~jthread()
|
||||
{
|
||||
if (joinable())
|
||||
{
|
||||
request_stop();
|
||||
join();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### 3.2.3.4 其他成员
|
||||
|
||||
其他成员基本上是在thread上进行操作,然后对外暴露了一个接口,例如:
|
||||
|
||||
```cpp
|
||||
[[nodiscard]] bool
|
||||
joinable() const noexcept
|
||||
{
|
||||
return _M_thread.joinable();
|
||||
}
|
||||
|
||||
join()
|
||||
{
|
||||
_M_thread.join();
|
||||
}
|
||||
|
||||
void
|
||||
detach()
|
||||
{
|
||||
_M_thread.detach();
|
||||
}
|
||||
|
||||
[[nodiscard]] id
|
||||
get_id() const noexcept
|
||||
{
|
||||
return _M_thread.get_id();
|
||||
}
|
||||
|
||||
[[nodiscard]] native_handle_type
|
||||
native_handle()
|
||||
{
|
||||
return _M_thread.native_handle();
|
||||
}
|
||||
|
||||
[[nodiscard]] static unsigned
|
||||
hardware_concurrency() noexcept
|
||||
{
|
||||
return thread::hardware_concurrency();
|
||||
}
|
||||
```
|
||||
|
||||
剩下一些是对stop_source的操作:
|
||||
|
||||
```cpp
|
||||
[[nodiscard]] stop_source
|
||||
get_stop_source() noexcept
|
||||
{
|
||||
return _M_stop_source;
|
||||
}
|
||||
|
||||
[[nodiscard]] stop_token
|
||||
get_stop_token() const noexcept
|
||||
{
|
||||
return _M_stop_source.get_token();
|
||||
}
|
||||
|
||||
bool request_stop() noexcept
|
||||
{
|
||||
return _M_stop_source.request_stop();
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 示例
|
||||
|
||||
cppreference中这个例子非常不错,在示例中用户工作函数传递了stop_source作为参数,在内部可以通过判断stop_requested(),如果停止了,我们可以做一些释放资源的操作,还是非常有用的。
|
||||
|
||||
触发的条件就是主线程执行了request_stop。
|
||||
|
||||
> https://en.cppreference.com/w/cpp/thread/stop_source
|
||||
98
site_extras/cpp-guides-cpp-string-split-methods.md
Normal file
98
site_extras/cpp-guides-cpp-string-split-methods.md
Normal file
@@ -0,0 +1,98 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/cpp-string-split-methods/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 字符串六种分割方法
|
||||
|
||||
通常我们在开发的时候会对一个长字符串依据分隔符进行分割,从而得到我们想要的字符串,大家都说C++字符串分割并没有那么方便,今天来总结一下5种方法分割字符串。
|
||||
|
||||
包含了从C++11到C++20的写法,以及C风格。
|
||||
|
||||
为了方便后续文章的讲解,我们先定义一个函数原型:
|
||||
|
||||
- 参数:两个字符串,一个表示原字符串,另一个表示分隔符
|
||||
|
||||
- 返回值:字符串数组
|
||||
|
||||
注:懒人版,可以从星球获取完整代码。
|
||||
|
||||
## 1.find分割
|
||||
|
||||
第一种方法便是大家常用的先找到分割符的位置,然后划分字符串,添加到数组中,于是有了下面的代码。
|
||||
|
||||
```cpp
|
||||
nt start = 0;
|
||||
int end = s.find(delim);
|
||||
std::vector<std::string> result;
|
||||
while (end != std::string::npos) {
|
||||
result.push_back(s.substr(start, end - start));
|
||||
start = end + delim.size();
|
||||
end = s.find(delim, start);
|
||||
}
|
||||
|
||||
result.push_back(s.substr(start, end - start));
|
||||
```
|
||||
|
||||
这种办法是否还能进行优化呢?
|
||||
|
||||
答案是肯定的,为了使得代码看起来更加优雅,我们可以每次删除前面已经输出的子串,然后find逻辑一致。
|
||||
|
||||
```cpp
|
||||
while (end != std::string::npos) {
|
||||
result.push_back(s.substr(0, end));
|
||||
s.erase(0, end + delim.size());
|
||||
end = s.find(delim);
|
||||
}
|
||||
```
|
||||
|
||||
## 2.C++20 Ranges与Views分割
|
||||
|
||||
C++20中我们可以使用 `std::ranges::views::split()` 创建一个分隔符的视图,然后使用transform,将每个子视图转换为 `std::string`。
|
||||
|
||||
```cpp
|
||||
auto split_transform_view = s | std::ranges::views::split(delim) |
|
||||
std::ranges::views::transform([](auto&& str) {
|
||||
return std::string(str.begin(), str.end());
|
||||
});
|
||||
```
|
||||
|
||||
是不是很简单,可能一些人没看懂,诶关系去看之前的C++20文章吧。
|
||||
|
||||
## 3.正则分割
|
||||
|
||||
使用 `std::regex` 对象构造分隔符模式,使用`std::sregex_token_iterator` 遍历由正则表达式模式分隔的子字符串,-1表示提取不匹配的字符串,即除了分割符的字符串。
|
||||
|
||||
```cpp
|
||||
std::regex r(delim);
|
||||
return {std::sregex_token_iterator(s.begin(), s.end(), r, -1),
|
||||
std::sregex_token_iterator()};
|
||||
```
|
||||
|
||||
## 4.istringstream分割
|
||||
|
||||
getline每次只能传递一个分隔符,于是分隔之后,需要继续跳过后续的分隔符。
|
||||
|
||||
```cpp
|
||||
std::istringstream ss(s);
|
||||
while (std::getline(ss, token, *(it = delim.begin()))) {
|
||||
result.push_back(token);
|
||||
it++;
|
||||
|
||||
while (it != delim.end() && ss.peek() == *(it)) {
|
||||
it++;
|
||||
ss.get();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5.C风格的strtok分割
|
||||
|
||||
使用 `strtok()` 将字符串分割成标记,然后while循环依次提取即可。
|
||||
|
||||
```cpp
|
||||
token = strtok((char*)s.c_str(), delim.c_str());
|
||||
while (token != NULL) {
|
||||
result.push_back(token);
|
||||
token = strtok(NULL, delim.c_str());
|
||||
}
|
||||
```
|
||||
|
||||
以上便是常用的几种方法,你还有其他方法吗?欢迎留言区见,本节懒人版可以从星球获取完整代码。
|
||||
148
site_extras/cpp-guides-cpython-extension-notes.md
Normal file
148
site_extras/cpp-guides-cpython-extension-notes.md
Normal file
@@ -0,0 +1,148 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/cpython-extension-notes/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# CPython 扩展开发笔记
|
||||
|
||||
本篇文章将会围绕最近给Apache提的一个feature为背景,展开讲讲CPython遇到的问题,以及尝试自己从0写一个库出来,代码也已经放星球了,感兴趣的同学可以去下载学习。
|
||||
|
||||
## 0.背景
|
||||
|
||||
最近在给apache arrow提的一个feature因为C++接口的变动引发其他语言的接口变动,一些测试也跟着需要修复。
|
||||
|
||||
像PyArrow熟悉的人应该一点也不陌生,这次接口变动也需要修改这个库,因为是在一个仓库里的,不然ci过不了。而PyArrow的实现是通过CPython实现的,之前也没特别学习CPython,改出了一堆问题,其中遇到两个问题比较重要,这里记录一下。
|
||||
|
||||
**问题1:初始化函数里面不支持其他类的默认构造。**
|
||||
|
||||
示例:
|
||||
|
||||
```
|
||||
def __init__(self, mode="only_valid", filter=Expression._scalar(True)):
|
||||
pass
|
||||
```
|
||||
|
||||
报错:
|
||||
|
||||
```
|
||||
TypeError: descriptor '_scalar' for 'pyarrow._compute.Expression' objects doesn't apply to a 'bool' object
|
||||
```
|
||||
|
||||
可以看到没识别出来,实际情况是Expression._scalar(True)合法的,我们看里面的实现:
|
||||
|
||||
```python
|
||||
@staticmethod
|
||||
def _scalar(value):
|
||||
cdef:
|
||||
Scalar scalar
|
||||
|
||||
if isinstance(value, Scalar):
|
||||
scalar = value
|
||||
else:
|
||||
scalar = lib.scalar(value)
|
||||
|
||||
return Expression.wrap(CMakeScalarExpression(scalar.unwrap()))
|
||||
```
|
||||
|
||||
可以看到,里面支持正常的bool类型,我怀疑这是cpython的限制,于是改为下面这种方式就可以了:
|
||||
|
||||
```python
|
||||
def __init__(self, mode="only_valid", filter=None):
|
||||
if filter is None:
|
||||
filter = Expression._scalar(True)
|
||||
```
|
||||
|
||||
**问题2:定义顺序**
|
||||
|
||||
当我使用后面创建的`_true`,每次传递进去的默认值是空,这个比较好理解,因为最后编译好了会翻译为一个`xxx.cpp`文件,根据C++规则前面读到的自然就是空了。
|
||||
|
||||
```python
|
||||
def __init__(self, mode="only_valid", filter=_true):
|
||||
pass
|
||||
|
||||
|
||||
cdef CExpression _true = CMakeScalarExpression(
|
||||
<shared_ptr[CScalar]> make_shared[CBooleanScalar](True)
|
||||
)
|
||||
```
|
||||
|
||||
好了,基于以上背景,我自己也想写一个例子出来,例如:使用C++写一个类,封装sort和sum,然后使用Python调用。
|
||||
|
||||
## 1.CPython完整例子
|
||||
|
||||
1. 创建一个.h文件
|
||||
|
||||
```cpp
|
||||
void sort(std::vector<int>& nums) {
|
||||
std::sort(nums.begin(), nums.end());
|
||||
}
|
||||
int sum(std::vector<int>& nums) {
|
||||
int sum = 0;
|
||||
for (int num : nums) {
|
||||
sum += num;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
||||
2) 创建foo.pyx
|
||||
|
||||
重要点:上面vector需要:
|
||||
|
||||
```
|
||||
from libcpp.vector cimport vector
|
||||
```
|
||||
|
||||
然后去定义一个class,调用C++的接口。
|
||||
|
||||
```
|
||||
cdef class PyFoo:
|
||||
cdef Foo* f
|
||||
|
||||
def __cinit__(self):
|
||||
self.f = new Foo()
|
||||
|
||||
def __dealloc__(self):
|
||||
del self.f
|
||||
|
||||
def sort(self, nums):
|
||||
cdef vector[int] c_nums = nums
|
||||
self.f.sort(c_nums)
|
||||
|
||||
def sum(self, nums):
|
||||
cdef vector[int] c_nums = nums
|
||||
return self.f.sum(c_nums)
|
||||
```
|
||||
|
||||
3. 创建setup.py文件
|
||||
|
||||
```python
|
||||
ext = Extension('Foo', sources=["foo.pyx"], language="c++", include_dirs=[numpy.get_include()])
|
||||
|
||||
setup(name="Foo", ext_modules = cythonize([ext]))
|
||||
```
|
||||
|
||||
4. 运行
|
||||
|
||||
```
|
||||
python3 setup.py build_ext --inplace
|
||||
```
|
||||
|
||||
最后,可以写一个测试脚本去使用自己写的python接口。
|
||||
|
||||
```python
|
||||
import Foo
|
||||
|
||||
f = Foo.PyFoo()
|
||||
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
|
||||
f.sort(nums)
|
||||
print("Sorted nums:", nums)
|
||||
print("Sum of nums:", f.sum(nums))
|
||||
```
|
||||
|
||||
CPython在一些项目中使用挺多的,学习起来吧~
|
||||
|
||||
运行:
|
||||
|
||||
```
|
||||
➜ cpython_examples python3 test.py
|
||||
Sorted nums: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
|
||||
Sum of nums: 44
|
||||
```
|
||||
271
site_extras/cpp-guides-curl-cpp-notes.md
Normal file
271
site_extras/cpp-guides-curl-cpp-notes.md
Normal file
@@ -0,0 +1,271 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/curl-cpp-notes/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# libcurl C++ 开发备忘
|
||||
|
||||
代码风格统一有助于团队协作与代码review,业界用的比较多的是google的风格,本节来点不一样的,看看咱们平时用的比较多的工具curl团队的代码规范是什么样子的。
|
||||
|
||||
curl简单说一下,它在命令行或脚本中传输数据非常有用,大家也肯定用过,其源码实现可以在github上查看
|
||||
|
||||
> https://github.com/curl/curl
|
||||
|
||||
下面我们来从几个方面看看curl的C语言开发规范。
|
||||
|
||||
[TOC]
|
||||
|
||||
## 命名
|
||||
|
||||
新的函数和变量名称应该是逻辑的、可理解的,并且根据它们的用途进行命名。
|
||||
|
||||
文件局部函数应该被声明为静态的,建议是小写字母名称。
|
||||
|
||||
## 缩进
|
||||
|
||||
只使用空格进行缩进,不使用制表符。每个新的开放大括号使用两个空格。
|
||||
|
||||
```
|
||||
if(something_is_true) {
|
||||
while(second_statement == fine) {
|
||||
moo();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 注释
|
||||
|
||||
由于编写的是 C89 代码,不允许使用 **//** 注释。它们直到 C99 标准才被引入。只使用 **/\* 注释 \*/**。
|
||||
|
||||
```
|
||||
/* 这是一个注释 */
|
||||
```
|
||||
|
||||
## 长行
|
||||
|
||||
curl 中的源代码永远不应该超过 79 列,即使在现代大屏幕和高分辨率屏幕时代,仍然有两个原因要保持这一点:
|
||||
|
||||
1. 较窄的列比较宽的列更容易阅读。有一个原因是报纸几十年甚至几个世纪来一直使用列。
|
||||
2. 较窄的列允许开发人员更容易地在不同的窗口中并排显示多个代码片段。它允许在同一个屏幕上并排显示两个或三个源代码窗口 - 以及多个终端和调试窗口。
|
||||
|
||||
## 大括号
|
||||
|
||||
在 if/while/do/for 表达式中,我们将开放大括号写在与关键字同一行,然后将闭合大括号设置在与初始关键字相同缩进级别的同一行。就像这样:
|
||||
|
||||
```
|
||||
if(age < 40) {
|
||||
/* 显然是年轻人 */
|
||||
}
|
||||
```
|
||||
|
||||
如果它们只包含一个一行语句,则可以省略大括号:
|
||||
|
||||
```
|
||||
if(!x)
|
||||
continue;
|
||||
```
|
||||
|
||||
对于函数,开放大括号应该写在单独的一行上:
|
||||
|
||||
```
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
## 'else' 在下一行
|
||||
|
||||
在使用大括号添加 **else** 子句到条件表达式时,我们将其添加到关闭大括号后的新行。就像这样:
|
||||
|
||||
```
|
||||
if(age < 40) {
|
||||
/* 显然是年轻人 */
|
||||
}
|
||||
else {
|
||||
/* 可能是脾气暴躁的 */
|
||||
}
|
||||
```
|
||||
|
||||
## 括号前不加空格
|
||||
|
||||
在使用 if/while/do/for 表达式时,关键字与开放括号之间不应有空格。就像这样:
|
||||
|
||||
```
|
||||
while(1) {
|
||||
/* 永远循环 */
|
||||
}
|
||||
```
|
||||
|
||||
## 使用布尔条件
|
||||
|
||||
在 if/while 条件中,我们更喜欢测试条件值,如布尔值与 TRUE 或 FALSE、指针与 NULL 或 != NULL 以及整数与零或非零,而不是:
|
||||
|
||||
```
|
||||
result = do_something();
|
||||
if(!result) {
|
||||
/* 出现了问题 */
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
## 条件中不要赋值
|
||||
|
||||
为了增加可读性并减少条件的复杂性,避免在 if/while 条件中进行变量赋值。不赞成这种风格:
|
||||
|
||||
```
|
||||
if((ptr = malloc(100)) == NULL)
|
||||
return NULL;
|
||||
```
|
||||
|
||||
而是鼓励更清晰地表达:
|
||||
|
||||
```
|
||||
ptr = malloc(100);
|
||||
if(!ptr)
|
||||
return NULL;
|
||||
```
|
||||
|
||||
## 新块在新行上
|
||||
|
||||
永远不会在同一行上写多个语句,即使是短的 if() 条件也不例外。
|
||||
|
||||
```
|
||||
if(a)
|
||||
return TRUE;
|
||||
else if(b)
|
||||
return FALSE;
|
||||
```
|
||||
|
||||
永远不要这样:
|
||||
|
||||
```
|
||||
if(a) return TRUE;
|
||||
else if(b) return FALSE;
|
||||
```
|
||||
|
||||
## 运算符周围加空格
|
||||
|
||||
请在 C 表达式中运算符的两侧使用空格。后缀 **(), [], ->, ., ++, --** 和一元 **+, -, !, ~, &** 操作符除外,它们不应该有空格。
|
||||
|
||||
示例:
|
||||
|
||||
```
|
||||
bla = func();
|
||||
who = name[0];
|
||||
age += 1;
|
||||
true = !false;
|
||||
size += -2 + 3 *
|
||||
|
||||
(a + b);
|
||||
ptr->member = a++;
|
||||
struct.field = b--;
|
||||
ptr = &address;
|
||||
contents = *pointer;
|
||||
complement = ~bits;
|
||||
empty = (!*string) ? TRUE : FALSE;
|
||||
```
|
||||
|
||||
## 返回值不加括号
|
||||
|
||||
在 'return' 语句中不加额外的括号:
|
||||
|
||||
```
|
||||
int works(void)
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
```
|
||||
|
||||
## sizeof 参数加括号
|
||||
|
||||
在代码中使用 sizeof 运算符时,我们更喜欢在其参数周围加上括号:
|
||||
|
||||
```
|
||||
int size = sizeof(int);
|
||||
```
|
||||
|
||||
## 列对齐
|
||||
|
||||
一些语句不能在单行上完成,因为行太长、语句太难读,或者是由于上述其他风格指南。在这种情况下,语句跨越多行。
|
||||
|
||||
如果一个连续行是表达式或子表达式的一部分,那么你应该在适当的列上对齐,以便能够清楚地知道它是语句的哪一部分。运算符不应该起始于连续行。在其他情况下,遵循 2 个空格的缩进指南。以下是来自 libcurl 的一些示例:
|
||||
|
||||
```
|
||||
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
|
||||
(handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
|
||||
(handle->set.httpreq == HTTPREQ_GET ||
|
||||
handle->set.httpreq == HTTPREQ_HEAD))
|
||||
/* 没有要求 HTTP/1.0 并且是 GET 或 HEAD 请求 */
|
||||
return TRUE;
|
||||
```
|
||||
|
||||
如果没有括号,使用默认缩进:
|
||||
|
||||
```
|
||||
data->set.http_disable_hostname_check_before_authentication =
|
||||
(0 != va_arg(param, long)) ? TRUE : FALSE;
|
||||
```
|
||||
|
||||
函数调用时使用开放括号:
|
||||
|
||||
```
|
||||
if(option) {
|
||||
result = parse_login_details(option, strlen(option),
|
||||
(userp ? &user : NULL),
|
||||
(passwdp ? &passwd : NULL),
|
||||
NULL);
|
||||
}
|
||||
```
|
||||
|
||||
与 "current open" 括号对齐:
|
||||
|
||||
```
|
||||
DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing "
|
||||
"server response left\n",
|
||||
(int)clipamount));
|
||||
```
|
||||
|
||||
## 平台相关代码
|
||||
|
||||
使用 **#ifdef HAVE_FEATURE** 进行条件代码。我们避免在 #ifdef 行中检查特定操作系统或硬件。HAVE_FEATURE 应该由 configure 脚本为类 Unix 系统生成,并且它们在其他系统的 `config-[system].h` 文件中硬编码。
|
||||
|
||||
我们还鼓励在 libcurl 构建时,使用可能为空或定义为常量的宏/函数,以使代码无缝。就像这个例子,其中 **magic()** 函数根据构建时的条件不同而工作:
|
||||
|
||||
```
|
||||
#ifdef HAVE_MAGIC
|
||||
void magic(int a)
|
||||
{
|
||||
return a + 2;
|
||||
}
|
||||
#else
|
||||
#define magic(x) 1
|
||||
#endif
|
||||
|
||||
int content = magic(3);
|
||||
```
|
||||
|
||||
## 不要 typedef 结构体
|
||||
|
||||
尽管可以使用结构体,但不要对其进行 typedef。使用 `struct name` 的方式来标识它们:
|
||||
|
||||
```
|
||||
struct something {
|
||||
void *valid;
|
||||
size_t way_to_write;
|
||||
};
|
||||
struct something instance;
|
||||
```
|
||||
|
||||
**不要这样**:
|
||||
|
||||
```
|
||||
typedef struct {
|
||||
void *wrong;
|
||||
size_t way_to_write;
|
||||
} something;
|
||||
something instance;
|
||||
```
|
||||
|
||||
本文翻译自:https://curl.se/dev/code-style.html
|
||||
|
||||
|
||||
!!! note "说明"
|
||||
本文为开发备忘,建议结合官方 libcurl 文档与具体项目错误码排查。
|
||||
100
site_extras/cpp-guides-how-to-read-open-source-cpp.md
Normal file
100
site_extras/cpp-guides-how-to-read-open-source-cpp.md
Normal file
@@ -0,0 +1,100 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/how-to-read-open-source-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 如何阅读开源 C++ 代码
|
||||
|
||||
## 如何秒懂阅读开源项目代码?
|
||||
|
||||
在实际项目或开源代码中,特别是C代码比较喜欢用宏,那么造成了一个很大问题:阅读代码非常的困难,调试也是另外一个问题,那么给你一个项目带有大量的宏,如何快速理解?
|
||||
|
||||
通常我们在面试的时候会遇到一个非常重要的知识点:gcc编译过程,大家可能对答如流,那么为了区分候选人的水平,引申出:你知道gcc哪些编译参数,各自参数有什么用?预处理阶段会发生什么?一般你会在这个阶段做些什么,对你有何帮助?
|
||||
|
||||
本节就一个开源项目为例,如何快速秒懂代码!
|
||||
|
||||
下面是一段libev的代码,其中有若干个宏,比如:
|
||||
|
||||
- EV_FREQUENT_CHECK
|
||||
- assert
|
||||
- `EV_P_`
|
||||
- ANHE_w
|
||||
- ANHE_at_cache
|
||||
|
||||
```cpp
|
||||
void noinline
|
||||
ev_timer_start (EV_P_ ev_timer *w) EV_THROW
|
||||
{
|
||||
if (expect_false (ev_is_active (w)))
|
||||
return;
|
||||
|
||||
ev_at (w) += mn_now;
|
||||
|
||||
assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
|
||||
|
||||
EV_FREQUENT_CHECK;
|
||||
|
||||
++timercnt;
|
||||
ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1);
|
||||
array_needsize (ANHE, timers, timermax, ev_active (w) + 1, EMPTY2);
|
||||
ANHE_w (timers [ev_active (w)]) = (WT)w;
|
||||
ANHE_at_cache (timers [ev_active (w)]);
|
||||
upheap (timers, ev_active (w));
|
||||
|
||||
EV_FREQUENT_CHECK;
|
||||
|
||||
/*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/
|
||||
}
|
||||
```
|
||||
|
||||
看起来是不是一愣一愣的,这段代码引出几个问题:
|
||||
|
||||
- 函数参数是几个?
|
||||
- 函数类型是?
|
||||
- 代码中ev_at是啥玩意?
|
||||
|
||||
为了秒懂代码,我们需要使用`-E`来得到预处理阶段宏展开之后的代码,方便我们理解与阅读。
|
||||
|
||||
展开之后,我们会得到:
|
||||
|
||||
```cpp
|
||||
void __attribute__ ((__noinline__))
|
||||
ev_timer_start (struct ev_loop *loop, ev_timer *w)
|
||||
{
|
||||
if (__builtin_expect ((!!((0 + ((ev_watcher *)(void *)(w))->active))),(0)))
|
||||
return;
|
||||
|
||||
((WT)(w))->at += ((loop)->mn_now);
|
||||
|
||||
|
||||
# 3881 "ev.c" 3 4
|
||||
((
|
||||
# 3881 "ev.c"
|
||||
("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.)
|
||||
# 3881 "ev.c" 3 4
|
||||
) ? (void) (0) : __assert_fail (
|
||||
# 388libev: ev_timer_start called with negative timer repeat value\", w->repeat >= 0.)"
|
||||
# 3881 "ev.c" 3 4
|
||||
, "ev.c", 3881, __PRETTY_FUNCTION__))
|
||||
# 3881 "ev.c"
|
||||
;
|
||||
|
||||
do { } while (0);
|
||||
|
||||
++((loop)->timercnt);
|
||||
ev_start (loop, (W)w, ((loop)->timercnt) + (4 - 1) - 1);
|
||||
if (__builtin_expect ((!!((((W)(w))->active + 1) > (((loop)->timermax)))),(0))) { int __attribute__ ((__unused__)) ocur_ = (((loop)->timermax)); (((loop)->timers)) = (ANHE *)array_realloc (sizeof (ANHE), (((loop)->timers)), &(((loop)->timermax)), (((W)(w))->active + 1)); ; };
|
||||
(((loop)->timers) [((W)(w))->active]).w = (WT)w;
|
||||
(((loop)->timers) [((W)(w))->active]).at = (((loop)->timers) [((W)(w))->active]).w->at;
|
||||
upheap (((loop)->timers), ((W)(w))->active);
|
||||
|
||||
do { } while (0);
|
||||
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
此时我们去理解代码,基本上没啥障碍了,但是还是不够清晰明了,为了突出你与其他候选人之间的差异,我提出几个问题:
|
||||
|
||||
- 上面显示了很多行数,可以去掉吗,怎么解决?
|
||||
- 上面assert这种系统宏非常的简单好理解,不需要我们展开它,你知道怎么做?
|
||||
- 在上面这二步展开中可能会出现问题,你知道发生了什么,如何解决?
|
||||
|
||||
好了,本节就先聊这么多,下一节继续分享,欢迎留言区探讨上面的答案!
|
||||
45
site_extras/cpp-guides-interesting-cpp-code-snippet.md
Normal file
45
site_extras/cpp-guides-interesting-cpp-code-snippet.md
Normal file
@@ -0,0 +1,45 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/interesting-cpp-code-snippet/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 一段有趣的 C++ 代码
|
||||
|
||||
## 0.导语
|
||||
|
||||
目标:如何获取参数lambda或者functor的参数个数呢?
|
||||
|
||||
本节将从模版 + `::*` + decay + decltype来实现!
|
||||
|
||||
## 1.实现
|
||||
|
||||
最终效果:
|
||||
|
||||
```cpp
|
||||
auto c1 = [](int x, double y) { return x * y; };
|
||||
std::cout << argument_count<decltype(c1)>::value << std::endl;
|
||||
MyClass f;
|
||||
std::cout << argument_count<decltype(f)>::value << std::endl;
|
||||
```
|
||||
|
||||
输出:2
|
||||
|
||||
我们思考一下这个问题,需要直到这几个点:
|
||||
|
||||
- 如何定位到functor与lambda的位置?
|
||||
- 如何获取到这个函数签名的参数数量?
|
||||
|
||||
对于第一个问题,我们可以使用`::*`便可以指向成员声明,对于functor与lambda都是`&std::decay<F>::type::operator())`。简单来说都是获取operator()这个声明的地址。
|
||||
|
||||
这里使用decay来移除cv限定符,以上述MyClass为例,到这里先通过`std::decay<F>::type`获取到MyClass类型,随后获取对应operator()的地址,然后传递给argument_count_impl。
|
||||
|
||||
```cpp
|
||||
template <typename F>
|
||||
using argument_count = decltype(argument_count_impl(&std::decay<F>::type::operator()));
|
||||
```
|
||||
|
||||
argument_count_impl的实现也比较简单,使用R (F::*)(A...)签名获取到对应的函数,这里使用了可变参数模版,`::*`,sizeof是用来获取参数数量,integral_constant则表示这个编译器常量类型为int,值为sizeof...(A)。
|
||||
|
||||
```cpp
|
||||
template <typename F, typename R, typename... A>
|
||||
static std::integral_constant<int, sizeof...(A)> argument_count_impl(R (F::*)(A...));
|
||||
```
|
||||
|
||||
基于此,便实现了获取Lambda or Functor参数个数的功能~
|
||||
148
site_extras/cpp-guides-print-1-to-100-without-loop.md
Normal file
148
site_extras/cpp-guides-print-1-to-100-without-loop.md
Normal file
@@ -0,0 +1,148 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-guides/print-1-to-100-without-loop/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 无循环打印 1-100
|
||||
|
||||
给大家设定一个条件:不使用循环,请打印出1-100个数字。
|
||||
|
||||
如果使用循环很简单了,那么你能想到多少种方法呢?
|
||||
|
||||
今天来给大家用一些C++的骚操作来写出这种代码,欢迎留言与转发~
|
||||
|
||||
这道题目其实非常简单,但却涵盖了很多面试考点,其中包括:
|
||||
|
||||
- 模版特化、便特化,如何编写递归模版
|
||||
- CRTP
|
||||
- std::copy、std::iota、std::transform如何使用,各自算法实现
|
||||
- 类静态变量
|
||||
- 等等
|
||||
|
||||
## 1.递归
|
||||
|
||||
1-100可以拆为`5*5*4`,用三个函数去打印它,函数a cout一次,然后变量加1,函数b层层嵌套a重复5次,函数c层层嵌套b重复5次,最后在main函数中对c层层嵌套4次。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int a(int n) {
|
||||
std::cout << n++ << std::endl;
|
||||
return n;
|
||||
}
|
||||
|
||||
int b(int n) { return a(a(a(a(a(n))))); }
|
||||
|
||||
int c(int n) { return b(b(b(b(b(n))))); }
|
||||
|
||||
int main() {
|
||||
c(c(c(c(1))));
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 2.模版重载
|
||||
|
||||
使用模版与特化来处理,当迭代100时只输出100,否则输出I,并且+1递归处理。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
template <int I>
|
||||
struct JustPrint : public JustPrint<I + 1> {
|
||||
JustPrint() : JustPrint<I + 1>() { std::cout << I << " "; }
|
||||
};
|
||||
|
||||
template <>
|
||||
struct JustPrint<100> {
|
||||
JustPrint<100>() { std::cout << 1 << " "; }
|
||||
};
|
||||
|
||||
int main() { JustPrint<1> j; }
|
||||
```
|
||||
|
||||
## 3.CRTP
|
||||
|
||||
方式3基于方式2,将其改造为crtp编程风格,是不是有点看不懂了,嘿嘿。
|
||||
|
||||
下面struct可以被替换为class,这里我用类来描述。其实就是两个类,第一个类Print为父类,打印每次的I,并调用子类,子类PrintDerived即成Print,并将自己传递给父类,子类是一个重载类,控制递归终止。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
template <typename Derived, int I>
|
||||
struct Print {
|
||||
Print() {
|
||||
std::cout << I << " ";
|
||||
Derived::next();
|
||||
}
|
||||
};
|
||||
|
||||
template <int I>
|
||||
struct PrintDerived : public Print<PrintDerived<I>, I> {
|
||||
static void next() { PrintDerived<I + 1>(); }
|
||||
};
|
||||
template <>
|
||||
struct PrintDerived<100> : public Print<PrintDerived<100>, 100> {
|
||||
static void next() {}
|
||||
};
|
||||
|
||||
int main() {
|
||||
PrintDerived<1> j;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 4.类静态变量
|
||||
|
||||
创建一个Test数组,元素为100个,静态变量每次累加。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class Test {
|
||||
static int i;
|
||||
|
||||
public:
|
||||
Test() { cout << ++i << endl; }
|
||||
};
|
||||
int Test::i;
|
||||
int main() {
|
||||
Test a[100];
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 5.使用算法库
|
||||
|
||||
使用`std::for_each`简单粗暴。
|
||||
|
||||
```cpp
|
||||
int main() {
|
||||
std::vector<int> l(100);
|
||||
std::iota(l.begin(), l.end(), 1);
|
||||
std::for_each(l.begin(), l.end(), [](int& n) { std::cout << n << std::endl; });
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 6.C++20 ranges
|
||||
|
||||
使用C++20的std::views,在std::copy时打印。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <ranges>
|
||||
int main() {
|
||||
auto numbers = std::views::iota(1, 100 + 1);
|
||||
std::copy(numbers.begin(), numbers.end(), std::ostream_iterator<int>(std::cout, "\n"));
|
||||
}
|
||||
```
|
||||
|
||||
这个方式继续改造,还有一种实现,使用std::transform。
|
||||
|
||||
```cpp
|
||||
auto range = std::views::transform(std::ranges::iota_view{1, 101}, [](const auto& x) {
|
||||
std::cout << x << std::endl;
|
||||
return x;
|
||||
});
|
||||
std::vector<int> a(range.begin(), range.end());
|
||||
```
|
||||
147
site_extras/cpp-idioms-avoid-default-constructor.md
Normal file
147
site_extras/cpp-idioms-avoid-default-constructor.md
Normal file
@@ -0,0 +1,147 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/avoid-default-constructor/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 避免默认构造函数
|
||||
|
||||
在 C++ 中,有一些容器通过 `resize()` 方法调整大小时,默认构造函数会被调用,这可能并不是我们想要的行为。本文将介绍如何使用自定义分配器来控制这一过程,避免默认构造的调用。
|
||||
|
||||
示例1:
|
||||
|
||||
```cpp
|
||||
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
vec.resize(5);
|
||||
vec.resize(10);
|
||||
```
|
||||
|
||||
你知道此时输出什么吗?
|
||||
|
||||
答案是:
|
||||
|
||||
```
|
||||
[0, 1, 2, 3, 4]
|
||||
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
|
||||
```
|
||||
|
||||
这里需要明白几点内容:
|
||||
|
||||
**第一:为何resize回去之后的数据变为了0,发生了什么?**
|
||||
|
||||
**第二:如果我想要原来的数据,怎么做?即我想要输出结果是:**
|
||||
|
||||
```cpp
|
||||
[0, 1, 2, 3, 4]
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
```
|
||||
|
||||
**第三:如果vector的成员没有默认构造函数会发生什么?**
|
||||
|
||||
**第四:resize有什么限制?**
|
||||
|
||||
那么本节就来研究一下这个强大的功能,如何让resize避免调用默认构造。
|
||||
|
||||
注:篇幅有限,懒人版本节所有代码更新于星球。
|
||||
|
||||
## 1.resize剖析
|
||||
|
||||
为了让本文更加丝滑,我使用了下面示例,禁止Foo的构造,然后vector上面resize它。
|
||||
|
||||
```cpp
|
||||
class Foo {
|
||||
public:
|
||||
Foo() = delete;
|
||||
|
||||
private:
|
||||
int a;
|
||||
};
|
||||
|
||||
std::vector<Foo> f;
|
||||
f.resize(10);
|
||||
```
|
||||
|
||||
此时会编译错误,我们可以看到一堆报错信息。
|
||||
|
||||
第一个问题:可以看到调用栈到了`__uninitialized_default_n`,此时会去检查当前类型是否是平凡类型,这便是resize的第一个限制!
|
||||
|
||||
```cpp
|
||||
required from '_ForwardIterator std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Foo*; _Size = long unsigned int]'
|
||||
710 | return __uninitialized_default_n_1<__is_trivial(_ValueType)
|
||||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
711 | && __can_fill>::
|
||||
```
|
||||
|
||||
第二个问题:由于我们禁止了默认构造,那么分配器在原地址placement new 一个默认对象的时候失败了,此时便报错,这便是第二个限制!
|
||||
|
||||
```cpp
|
||||
gcc/14.1.0_1/include/c++/14/bits/stl_construct.h:119:7: error: use of deleted function 'Foo::Foo()'
|
||||
119 | ::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
|
||||
| ^~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
那么说到这里了,便可以进入正文了,可以看到resize的时候会去使用分配器去分配内存,当传递的大小大于size(此时假设在capacity内,即地址有效),那么此时会使用分配器placement new一个默认构造函数的对象。
|
||||
|
||||
gcc的源码实现可以放在这里给大家看一下,很简单吧?就是调用construct。
|
||||
|
||||
```cpp
|
||||
__try
|
||||
{
|
||||
typedef __gnu_cxx::__alloc_traits<_Allocator> __traits;
|
||||
for (; __n > 0; --__n, (void)++__cur)
|
||||
__traits::construct(__alloc, std::__addressof(*__cur));
|
||||
return __cur;
|
||||
}
|
||||
__catch(...)
|
||||
{
|
||||
std::_Destroy(__first, __cur, __alloc);
|
||||
__throw_exception_again;
|
||||
}
|
||||
```
|
||||
|
||||
好了,resize原理讲明白了,我们来讲讲一开始的问题。
|
||||
|
||||
## 2.避免调用默认构造
|
||||
|
||||
如何避免调用默认构造呢?
|
||||
|
||||
那其实很简单了,就是屏蔽调gcc默认的construct,怎么屏蔽了?
|
||||
|
||||
这里便用到了vector的第二个参数:分配器!
|
||||
|
||||
## 3.分配器
|
||||
|
||||
为了解决这个问题,我们可以使用自定义分配器。自定义分配器可以控制对象的构造行为,允许我们选择在调用 `resize` 时是否使用默认构造。以下是一个简单的自定义分配器实现,只贴了核心代码。
|
||||
|
||||
```cpp
|
||||
template <class T>
|
||||
class no_init_alloc {
|
||||
public:
|
||||
using value_type = T;
|
||||
// Override construct method to do nothing
|
||||
template <class U>
|
||||
void construct(U* p) {
|
||||
// Do nothing, memory is not initialized
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
我们只需要在construct不做任何事情即可,此时便可以使用它,即:
|
||||
|
||||
```cpp
|
||||
std::vector<Foo, no_init_alloc<Foo>> std_vec;
|
||||
```
|
||||
|
||||
此时便可以得到:
|
||||
|
||||
```cpp
|
||||
[0, 1, 2, 3, 4]
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
```
|
||||
|
||||
而不是:
|
||||
|
||||
```
|
||||
[0, 1, 2, 3, 4]
|
||||
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
|
||||
```
|
||||
|
||||
好了,你学会了吗?
|
||||
|
||||
> 本节完
|
||||
@@ -0,0 +1,35 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/class-template-over-function-template/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 类模板优于函数模板
|
||||
|
||||
https://stackoverflow.com/questions/5688355/partial-specialisation-of-member-function-with-non-type-parameter
|
||||
|
||||
最近看到一个很有意思的模版问题,看看大家对函数模版与类模版的基础掌握的如何,对于下面这个例子会出现什么问题?
|
||||
|
||||
你一般使用什么方法进行修复?
|
||||
|
||||
```cpp
|
||||
template <typename T, int R>
|
||||
struct foo {
|
||||
foo(const T& v) : value_(v) {}
|
||||
|
||||
void bar() {
|
||||
std::cout << "Generic" << std::endl;
|
||||
for (int i = 0; i < R; ++i) std::cout << value_ << std::endl;
|
||||
}
|
||||
|
||||
T value_;
|
||||
};
|
||||
|
||||
template <>
|
||||
void foo<float, 3>::bar() {
|
||||
std::cout << "Float" << std::endl;
|
||||
for (int i = 0; i < 3; ++i) std::cout << value_ << std::endl;
|
||||
}
|
||||
|
||||
template <int R>
|
||||
void foo<double, R>::bar() {
|
||||
std::cout << "Double" << std::endl;
|
||||
for (int i = 0; i < R; ++i) std::cout << value_ << std::endl;
|
||||
}
|
||||
```
|
||||
97
site_extras/cpp-idioms-dependency-injection-cpp.md
Normal file
97
site_extras/cpp-idioms-dependency-injection-cpp.md
Normal file
@@ -0,0 +1,97 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/dependency-injection-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 依赖注入
|
||||
|
||||
最近星球里面有个小伙伴让更新一下依赖注入,于是写出了这篇文章,来从实际的例子讲解,本文会讲解一些原理与实现,完整的实现代码懒人版放在星球中,我们开始正文。
|
||||
|
||||
大纲:
|
||||
|
||||
- 直接依赖
|
||||
- 接口依赖注入
|
||||
- 模版依赖注入
|
||||
|
||||
依赖注入是一种常用的设计模式,通常会采用接口/模版的方式提高代码的可测性与维护性,下面我们来举个例子。
|
||||
|
||||
假设有一个用户服务类UserService,需要通过HTTP客户端与远程服务器进行通信,在这种情况下我们可能会写出如下三种实现。
|
||||
|
||||
## 1.直接依赖
|
||||
|
||||
UserService内部直接依赖HttpClient,例如:
|
||||
|
||||
```cpp
|
||||
class HttpClient {
|
||||
public:
|
||||
std::string Get(const std::string& url);
|
||||
void Post(const std::string& url, const std::string& data);
|
||||
};
|
||||
|
||||
class UserService {
|
||||
private:
|
||||
HttpClient m_httpClient;
|
||||
};
|
||||
```
|
||||
|
||||
UserService内部通常会有一些方法去操作m_httpClient,这种方式简单粗暴,但是UserService与具体的HttpClient相耦合,导致难以替换依赖对象,也难以进行单元测试。
|
||||
|
||||
于是引出了后面两个方法。
|
||||
|
||||
## 2.接口依赖注入
|
||||
|
||||
我们的目标是期望测试的时候很方便的测试,而不需要创建一个具体的类,可以由用户mock出一个类去测试,那么我们可以想到接口,将HttpClient抽出来,得到:
|
||||
|
||||
```cpp
|
||||
struct IHttpClient {
|
||||
virtual std::string Get(const std::string& url) = 0;
|
||||
virtual void Post(const std::string& url, const std::string& data) = 0;
|
||||
virtual ~IHttpClient() = default;
|
||||
};
|
||||
class UserService {
|
||||
private:
|
||||
std::unique_ptr<IHttpClient> m_httpClient;
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
那么在测试的时候便可以mock出一个client进行测试,例如:
|
||||
|
||||
```cc
|
||||
class MockHttpClient : public IHttpClient {
|
||||
public:
|
||||
MOCK_METHOD(std::string, Get, (const std::string& url), (override));
|
||||
MOCK_METHOD(void, Post, (const std::string& url, const std::string& data), (override));
|
||||
};
|
||||
|
||||
auto mockHttpClient = std::make_unique<MockHttpClient>();
|
||||
UserService userService(std::move(mockHttpClient));
|
||||
```
|
||||
|
||||
经过以上改造,我们可以做到:
|
||||
|
||||
- 在 .cc 文件中隐藏实现细节
|
||||
- 针对抽象接口工作
|
||||
- 在对象构造期间注入依赖项
|
||||
|
||||
## 3.模版依赖注入
|
||||
|
||||
模板依赖注入通过C++模板技术,将依赖对象作为模板参数传递给`UserService`。在实例化模板时,指定具体的HTTP客户端实现。这种方法在编译时解决依赖问题,无需虚函数调用,提高了性能。同时,也使得`UserService`类可以灵活地与不同的HTTP客户端实现进行集成,并且易于进行单元测试。
|
||||
|
||||
```cpp
|
||||
template <typename THttpClient>
|
||||
class UserService {
|
||||
private:
|
||||
THttpClient m_httpClient;
|
||||
};
|
||||
```
|
||||
|
||||
在这种情况下比较好测试,例如:
|
||||
|
||||
```cpp
|
||||
UserService<MockHttpClient> userService;
|
||||
```
|
||||
|
||||
这种方式有如下好处:
|
||||
|
||||
- 在模板实例化期间注入依赖项
|
||||
- 无需虚拟调用(注意 THttpClient 不是接口,因此可以在编译时解析调用)
|
||||
|
||||
以上便是本节要讲的所有内容,本节完整代码放于星球,欢迎订阅下载!
|
||||
11
site_extras/cpp-idioms-header-only-vs-implementation.md
Normal file
11
site_extras/cpp-idioms-header-only-vs-implementation.md
Normal file
@@ -0,0 +1,11 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/header-only-vs-implementation/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ Header-Only 与实现分离
|
||||
|
||||
最近看到一些小伙伴问到了几个比较有趣的问题,这里总结一下,这些都是实际面试中出现过的问题,看看你知道多少,考察一下底子。
|
||||
|
||||
**面试问题1:你通常编写代码的风格是什么?Header-Only?还是声明与实现分离?**
|
||||
|
||||
**面试问题2:C++里面是否所有的函数可以分离实现与声明?为什么?**
|
||||
|
||||
**面试问题3:模版的声明与实现分离有哪些方法?请举例说明各自优缺点,适用场景?**
|
||||
75
site_extras/cpp-idioms-lazy-evaluation-cpp.md
Normal file
75
site_extras/cpp-idioms-lazy-evaluation-cpp.md
Normal file
@@ -0,0 +1,75 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/lazy-evaluation-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 延迟计算惯用法
|
||||
|
||||
---
|
||||
|
||||
在软件开发中,延迟计算(**lazy evaluation or call-by-need**)是一种强大的技术,它允许我们推迟表达式的计算,直到真正需要的时候才执行。
|
||||
|
||||
这种技术在处理大规模数据集或需要动态计算的情况下特别有用。
|
||||
|
||||
### 1.什么是延迟计算?
|
||||
|
||||
延迟计算是指推迟表达式的计算,直到它们真正需要的时候才执行。这种技术的优点在于可以提高程序的效率和性能,尤其是在处理大规模数据集或需要动态计算的情况下。
|
||||
|
||||
延迟计算的实现通常通过延迟函数调用或延迟表达式求值来实现。这意味着表达式的计算被推迟到它们被使用的时候,而不是在定义它们的时候就立即执行。
|
||||
|
||||
### 2.几种实现方法
|
||||
|
||||
在 C++ 中,我们有多种方法来实现延迟计算。下面是一些常见的方法:
|
||||
|
||||
1. **Lambda 表达式**:Lambda 表达式可以用来表示一个匿名函数,可以在需要的地方进行延迟计算。
|
||||
|
||||
```cpp
|
||||
auto delayedCalculation = []() {
|
||||
std::cout << "延迟计算" << std::endl;
|
||||
return 42;
|
||||
};
|
||||
```
|
||||
|
||||
2. **std::function**:`std::function` 可以用于封装函数,使得函数的执行可以延迟到后面的某个时刻。
|
||||
|
||||
```cpp
|
||||
std::function<int()> delayedCalculation = []() {
|
||||
std::cout << "延迟计算" << std::endl;
|
||||
return 42;
|
||||
};
|
||||
```
|
||||
|
||||
3. **std::bind**:`std::bind` 可以用于绑定函数和参数,并生成一个可调用对象,延迟执行函数调用。
|
||||
|
||||
```cpp
|
||||
auto delayedCall = std::bind(delayedCalculation, 42);
|
||||
```
|
||||
|
||||
4. **函数指针**:通过指向函数的指针,可以在需要的时候调用相应的函数,实现延迟计算。
|
||||
|
||||
```cpp
|
||||
void delayedCalculation() {
|
||||
std::cout << "延迟计算" << std::endl;
|
||||
}
|
||||
|
||||
void (*funcPtr)() = &delayedCalculation;
|
||||
(*funcPtr)();
|
||||
```
|
||||
|
||||
5. **惰性求值**:惰性求值是一种延迟计算的范式,它延迟表达式的求值直到它真正需要的时候。
|
||||
|
||||
```cpp
|
||||
auto it = std::begin(vec);
|
||||
std::cout << "第一个元素:" << *it << std::endl;
|
||||
```
|
||||
|
||||
6. **生成器**:生成器是一种用于延迟生成序列的技术,允许按需生成序列中的元素,而不是一次性生成所有元素。
|
||||
|
||||
```cpp
|
||||
std::vector<int> generateSequence(int n) {
|
||||
std::vector<int> result;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
result.push_back(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
除此之外,还有哪些实现呢?欢迎与我一起探讨。
|
||||
134
site_extras/cpp-idioms-lookup-table-idiom.md
Normal file
134
site_extras/cpp-idioms-lookup-table-idiom.md
Normal file
@@ -0,0 +1,134 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/lookup-table-idiom/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 查表法惯用法
|
||||
|
||||
```cpp
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <cmath>
|
||||
#include <random>
|
||||
|
||||
|
||||
const int HLL_COUNT = 16;
|
||||
|
||||
|
||||
static float harmonic_mean_table(const uint64_t* data) {
|
||||
static const float harmonic_tables[16] = {
|
||||
1.0f / static_cast<float>(1L << 0),
|
||||
1.0f / static_cast<float>(1L << 1),
|
||||
1.0f / static_cast<float>(1L << 2),
|
||||
1.0f / static_cast<float>(1L << 3),
|
||||
1.0f / static_cast<float>(1L << 4),
|
||||
1.0f / static_cast<float>(1L << 5),
|
||||
1.0f / static_cast<float>(1L << 6),
|
||||
1.0f / static_cast<float>(1L << 7),
|
||||
1.0f / static_cast<float>(1L << 8),
|
||||
1.0f / static_cast<float>(1L << 9),
|
||||
1.0f / static_cast<float>(1L << 10),
|
||||
1.0f / static_cast<float>(1L << 11),
|
||||
1.0f / static_cast<float>(1L << 12),
|
||||
1.0f / static_cast<float>(1L << 13),
|
||||
1.0f / static_cast<float>(1L << 14),
|
||||
1.0f / static_cast<float>(1L << 15),
|
||||
};
|
||||
|
||||
float harmonic_mean = 0.0f;
|
||||
for (int i = 0; i < HLL_COUNT; ++i) {
|
||||
harmonic_mean += harmonic_tables[data[i]];
|
||||
}
|
||||
|
||||
return harmonic_mean;
|
||||
}
|
||||
|
||||
static float harmonic_mean_calc(const uint64_t* data) {
|
||||
float harmonic_mean = 0.0f;
|
||||
for (int i = 0; i < HLL_COUNT; ++i) {
|
||||
harmonic_mean += powf(2.0f, -data[i]);
|
||||
}
|
||||
|
||||
return harmonic_mean;
|
||||
}
|
||||
|
||||
|
||||
uint64_t global_data[HLL_COUNT];
|
||||
|
||||
static void CustomArguments(benchmark::internal::Benchmark* b) {
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
std::uniform_int_distribution<uint64_t> dis(0, HLL_COUNT - 1);
|
||||
|
||||
for (int i = 0; i < HLL_COUNT; ++i) {
|
||||
global_data[i] = dis(gen);
|
||||
}
|
||||
}
|
||||
|
||||
static void BM_HarmonicMeanTable(benchmark::State& state) {
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(harmonic_mean_table(global_data));
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_HarmonicMeanTable)->Apply(CustomArguments);
|
||||
|
||||
|
||||
static void BM_HarmonicMeanCalc(benchmark::State& state) {
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(harmonic_mean_calc(global_data));
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_HarmonicMeanCalc)->Apply(CustomArguments);
|
||||
```
|
||||
|
||||
https://quick-bench.com/q/KtYyI4wutSurcnCrEezhRrH3Oks
|
||||
|
||||
> https://github.com/StarRocks/starrocks/pull/16351
|
||||
|
||||
## std::inplace_merge vs std::merge
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <numeric>
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
|
||||
std::vector<int> generateTestData(int size) {
|
||||
std::vector<int> vec(size);
|
||||
|
||||
for (int i = 0; i < size / 2; ++i) {
|
||||
vec[i] = 2 * i + 1;
|
||||
}
|
||||
|
||||
for (int i = size / 2; i < size; ++i) {
|
||||
vec[i] = 2 * (i - size / 2) + 2;
|
||||
}
|
||||
|
||||
return vec;
|
||||
}
|
||||
|
||||
static void BM_Merge(benchmark::State& state) {
|
||||
state.PauseTiming();
|
||||
std::vector<int> vec = generateTestData(state.range(0) * 2);
|
||||
std::vector<int> result(state.range(0) * 2);
|
||||
state.ResumeTiming();
|
||||
for (auto _ : state) {
|
||||
std::merge(vec.begin(), vec.begin() + state.range(0), vec.begin() + state.range(0), vec.end(), result.begin());
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_Merge)->Range(8, 8 << 10);
|
||||
|
||||
static void BM_InplaceMerge(benchmark::State& state) {
|
||||
state.PauseTiming();
|
||||
std::vector<int> vec = generateTestData(state.range(0) * 2);
|
||||
std::vector<int>::iterator middle = vec.begin() + state.range(0);
|
||||
state.ResumeTiming();
|
||||
|
||||
for (auto _ : state) {
|
||||
std::inplace_merge(vec.begin(), middle, vec.end());
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_InplaceMerge)->Range(8, 8 << 10);
|
||||
```
|
||||
|
||||
https://quick-bench.com/q/u1WQpxF-KxrvW2s4mrnPkC6ZvLw
|
||||
|
||||
> https://github.com/StarRocks/starrocks/pull/14609
|
||||
101
site_extras/cpp-idioms-member-pointer-type-info.md
Normal file
101
site_extras/cpp-idioms-member-pointer-type-info.md
Normal file
@@ -0,0 +1,101 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/member-pointer-type-info/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 成员指针与类型信息
|
||||
|
||||
`::*`,估计99%的人都没用过,甚至没见过,可以留言区打出来!本节将会从0讲解语法,并使用一个项目中的实际例子来实战该用法。
|
||||
|
||||
[TOC]
|
||||
|
||||
## 1.什么是`::*`
|
||||
|
||||
`C::*` 是 C++ 中的**成员指针**语法,表示指向某个类 `C` 成员的指针。这个语法用于指向类的成员变量或成员函数。与普通指针不同,成员指针不是指向某个对象的具体内存地址,而是指向类中成员的**位置**,并且需要与类的对象实例一起使用。
|
||||
|
||||
### 1.1 语法
|
||||
|
||||
- `T C::*` 是一个指向类 `C` 中类型为 `T` 的成员变量的指针。
|
||||
- `R (C::*)(Args...)` 是一个指向类 `C` 中返回类型为 `R`,参数列表为 `Args...` 的成员函数的指针。
|
||||
|
||||
### 1.2 成员变量指针
|
||||
|
||||
成员变量指针指向某个类的成员变量,使用 `T C::*` 这种形式。
|
||||
|
||||
例如:下面示例中定义了一个成员指针 `ptr`,它指向 `MyClass` 类的 `x` 成员。`obj.*ptr` 通过成员指针访问对象的成员变量。
|
||||
|
||||
```cpp
|
||||
struct MyClass {
|
||||
int x;
|
||||
double y;
|
||||
};
|
||||
|
||||
int MyClass::*ptr = &MyClass::x;
|
||||
|
||||
MyClass obj;
|
||||
obj.x = 10;
|
||||
std::cout << "obj.x = " << obj.*ptr << std::endl;
|
||||
```
|
||||
|
||||
### 1.3 成员函数指针
|
||||
|
||||
成员函数指针指向类的成员函数,使用 `R (C::*)(Args...)` 这种形式。
|
||||
|
||||
示例:通过 `obj.*funcPtr()` 调用成员函数。
|
||||
|
||||
```cpp
|
||||
void (MyClass::*funcPtr)() const = &MyClass::print;
|
||||
MyClass obj;
|
||||
(obj.*funcPtr)();
|
||||
```
|
||||
|
||||
## 3.有什么用?
|
||||
|
||||
假设你有一个 ORM 框架,需要从成员指针中获取字段类型,生成对应列的类型,可以这样写:
|
||||
|
||||
```cpp
|
||||
struct User {
|
||||
std::string username;
|
||||
int user_id;
|
||||
};
|
||||
|
||||
// 自动生成数据库列的定义
|
||||
template <typename T, typename C>
|
||||
void generate_sql_column(T C::*member_ptr, const std::string& column_name) {
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
std::cout << column_name << " VARCHAR(255)" << std::endl;
|
||||
} else if constexpr (std::is_integral_v<T>) {
|
||||
std::cout << column_name << " INT" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
// 假设我们想自动为 User 类生成 SQL 表结构
|
||||
generate_sql_column(&User::username, "username");
|
||||
generate_sql_column(&User::user_id, "user_id");
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 4.实际项目衍生实用工具!
|
||||
|
||||
在实际项目中,我们可以使用`C::*`提取出对象与成员类型,怎么实现呢?
|
||||
|
||||
答案是:模版 + `C::*`
|
||||
|
||||
如下示例,我们便可以通过`value_type_from_member_pointer`与`class_type_from_member_pointer`来提取出对应的成员类型与类类型,非常方便的工具。
|
||||
|
||||
```cpp
|
||||
template <typename T, typename C>
|
||||
struct from_member_pointer_helper<T C::*> {
|
||||
using value_type = T;
|
||||
using class_type = C;
|
||||
};
|
||||
|
||||
template <auto Ptr>
|
||||
struct from_member_pointer : from_member_pointer_helper<typename std::remove_cvref_t<decltype(Ptr)>> {};
|
||||
|
||||
template <auto Ptr>
|
||||
using value_type_from_member_pointer = from_member_pointer<Ptr>::value_type;
|
||||
|
||||
template <auto Ptr>
|
||||
using class_type_from_member_pointer = from_member_pointer<Ptr>::class_type;
|
||||
```
|
||||
228
site_extras/cpp-idioms-mixin-idiom.md
Normal file
228
site_extras/cpp-idioms-mixin-idiom.md
Normal file
@@ -0,0 +1,228 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/mixin-idiom/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ Mixin 惯用法
|
||||
|
||||
大家好,我是光城,今天给大家分享C++那些事里面的一个惯用法:mixin
|
||||
|
||||
混合(Mixins)是Lisp中的一个概念。混合是类的一部分,意味着它旨在与其他类或混合组合在一起。
|
||||
常规独立类(例如Person)与混合的区别在于,混合模拟了一些小功能片段(例如打印或显示),并不用于独立使用。相反,它应该与需要此功能的其他类(例如Person)组合在一起。
|
||||
|
||||
因此,混合的目的是允许类似于多重继承的东西。
|
||||
|
||||
在C++汇总mixin的基本写法如下:
|
||||
|
||||
```cpp
|
||||
template <class Super>
|
||||
class Mixin : public Super {
|
||||
. /* mixin body */
|
||||
};
|
||||
```
|
||||
|
||||
或者
|
||||
|
||||
```cpp
|
||||
template<typename... Super>
|
||||
class Mixin : public Super... {
|
||||
public:
|
||||
Mixin() : Super...() {}
|
||||
// ...
|
||||
};
|
||||
```
|
||||
|
||||
**注:本节的所有示例代码可从星球获取。**
|
||||
|
||||
## 示例1:缩放与旋转
|
||||
|
||||
假设我们要对一个长方形/正方形进行缩放、旋转、添加边框等,这些操作都会影响其宽度与高度,我们可以使用mixin来实现。
|
||||
|
||||
首先,我们可以定义好正常形与长方形作为mixin的基类。
|
||||
|
||||
```cpp
|
||||
// 正方形类
|
||||
class Square : public Shape {
|
||||
public:
|
||||
Square(int sideLength) : sideLength(sideLength) {}
|
||||
int GetWidth() const override { return sideLength; }
|
||||
int GetHeight() const override { return sideLength; }
|
||||
private:
|
||||
int sideLength;
|
||||
};
|
||||
|
||||
// 长方形类
|
||||
class Rectangle : public Shape {
|
||||
public:
|
||||
Rectangle(int width, int height) : width(width), height(height) {}
|
||||
int GetWidth() const override { return width; }
|
||||
int GetHeight() const override { return height; }
|
||||
private:
|
||||
int width;
|
||||
int height;
|
||||
};
|
||||
```
|
||||
|
||||
随后使用mixin子类去拓展功能,例如:一个缩放的mixin我们可以自定义一个类,它的宽度与高度等于scale乘以对应的宽高。
|
||||
|
||||
```cpp
|
||||
// 缩放的Mixin
|
||||
template <class Base, int ScaleX, int ScaleY>
|
||||
class Scale : public Base {
|
||||
public:
|
||||
int GetScaledWidth() const { return Base::GetWidth() * ScaleX; }
|
||||
int GetScaledHeight() const { return Base::GetHeight() * ScaleY; }
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
像这种场景非常适合使用mixin。
|
||||
|
||||
使用的时候:
|
||||
|
||||
```cpp
|
||||
using ModifiedShape = Border<RotateBy90<Scale<Square, 2, 1>>, 10>;
|
||||
```
|
||||
|
||||
## 示例2:redo与undo
|
||||
|
||||
完整示例模拟一个redo与undo操作,我们便可以在数据之间来回的切换。`Redoable<Undoable<Number>> `,在这里我们可以将这些类混合到一起使用了。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Number {
|
||||
typedef int value_type;
|
||||
int n;
|
||||
void set(int v) {
|
||||
n = v;
|
||||
}
|
||||
int get() const {
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename BASE, typename T = typename BASE::value_type>
|
||||
struct Undoable : public BASE {
|
||||
typedef T value_type;
|
||||
T before;
|
||||
void set(T v) {
|
||||
before = BASE::get();
|
||||
BASE::set(v);
|
||||
}
|
||||
void undo() {
|
||||
BASE::set(before);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename BASE, typename T = typename BASE::value_type>
|
||||
struct Redoable : public BASE {
|
||||
typedef T value_type;
|
||||
T after;
|
||||
void set(T v) {
|
||||
after = v;
|
||||
BASE::set(v);
|
||||
}
|
||||
void redo() {
|
||||
BASE::set(after);
|
||||
}
|
||||
};
|
||||
|
||||
typedef Redoable<Undoable<Number>> ReUndoableNumber;
|
||||
|
||||
int main() {
|
||||
ReUndoableNumber mynum;
|
||||
mynum.set(42);
|
||||
mynum.set(84);
|
||||
cout << mynum.get() << '\n'; // Output: 84
|
||||
mynum.undo();
|
||||
cout << mynum.get() << '\n'; // Output: 42
|
||||
mynum.redo();
|
||||
cout << mynum.get() << '\n'; // Output: back to 84
|
||||
}
|
||||
```
|
||||
|
||||
## 示例3:重复打印
|
||||
|
||||
再举一个拼积木的例子:重复打印。
|
||||
|
||||
首先,有一个类,我们可以print这个人的名字。
|
||||
|
||||
```cpp
|
||||
class Name
|
||||
{
|
||||
public:
|
||||
Name(std::string firstName, std::string lastName)
|
||||
: firstName_(std::move(firstName))
|
||||
, lastName_(std::move(lastName)) {}
|
||||
|
||||
void print() const
|
||||
{
|
||||
std::cout << lastName_ << ", " << firstName_ << '\n';
|
||||
}
|
||||
|
||||
private:
|
||||
std::string firstName_;
|
||||
std::string lastName_;
|
||||
};
|
||||
```
|
||||
|
||||
那如果我想重复打印呢?
|
||||
|
||||
我们可以这样玩,使用mixin,将Name类传递进去。
|
||||
|
||||
```cpp
|
||||
template<typename Printable>
|
||||
struct RepeatPrint : Printable
|
||||
{
|
||||
explicit RepeatPrint(Printable const& printable) : Printable(printable) {}
|
||||
void repeat(unsigned int n) const
|
||||
{
|
||||
while (n-- > 0)
|
||||
{
|
||||
this->print();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Printable>
|
||||
RepeatPrint<Printable> repeatPrint(Printable const& printable)
|
||||
{
|
||||
return RepeatPrint<Printable>(printable);
|
||||
}
|
||||
```
|
||||
|
||||
使用:
|
||||
|
||||
```
|
||||
Name ned("Eddard", "Stark");
|
||||
repeatPrint(ned).repeat(10);
|
||||
```
|
||||
|
||||
此时,便得到重复n次的打印结果。
|
||||
|
||||
那么mixin比较适合什么场景呢?
|
||||
|
||||
- 保持原来的类不变,
|
||||
- 客户端代码不直接使用原始类,它需要将其包装到 mixin 中才能使用增强功能,
|
||||
|
||||
## 标准库
|
||||
|
||||
在标准库当中有一个使用mixin技术:std::nested_exception。
|
||||
|
||||
std::nested_exception 是一个多态 mixin 类,它可以捕获并存储当前异常,从而可以在彼此之间嵌套任意类型的异常。
|
||||
|
||||
```cpp
|
||||
template <typename _Except>
|
||||
struct _Nested_exception : public _Except, public nested_exception
|
||||
{}
|
||||
```
|
||||
|
||||
在源码中我们可以看到使用了nested_exception作为mixin的基类。
|
||||
|
||||
## 参考
|
||||
|
||||
> https://cedanet.com.au/ceda/Xc++/$mixin/mixins-in-straight-c++.php
|
||||
>
|
||||
> https://www.fluentcpp.com/2017/12/12/mixin-classes-yang-crtp/
|
||||
>
|
||||
> https://stackoverflow.com/questions/18773367/what-are-mixins-as-a-concept
|
||||
51
site_extras/cpp-idioms-trigraphs-cpp.md
Normal file
51
site_extras/cpp-idioms-trigraphs-cpp.md
Normal file
@@ -0,0 +1,51 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-idioms/trigraphs-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 三字母词
|
||||
|
||||
## C++那些事之删除三字母
|
||||
|
||||
C++17 之前,Trigraph 是用 ISO/IEC 646 等小字符代码编写程序的功能,在 C89 中引入。 ISO/IEC 646 缺少 C 中使用的以下字符,因此`??`请使用以下字符进行转义:
|
||||
|
||||
| 三字母内容 | 替换的内容 |
|
||||
| ---------- | ---------- |
|
||||
| `??=` | `#` |
|
||||
| `??(` | `[` |
|
||||
| `??)` | `]` |
|
||||
| `??<` | `{` |
|
||||
| `??>` | `}` |
|
||||
| `??/` | `\` |
|
||||
| `??!` | `|` |
|
||||
| `??-` | `~` |
|
||||
| `??'` | `^` |
|
||||
|
||||
`\?`它被转义以防止被三字母表替换。
|
||||
|
||||
C++17三字母被删除,`??=`等不再被替换。
|
||||
|
||||
## 示例
|
||||
|
||||
C++17之前:
|
||||
|
||||
```cpp
|
||||
std::cout << "??=" << std::endl;
|
||||
std::cout << "??(" << std::endl;
|
||||
std::cout << "?\?(" << std::endl;
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```
|
||||
#
|
||||
[
|
||||
??(
|
||||
```
|
||||
|
||||
C++17及之后:
|
||||
|
||||
```
|
||||
??=
|
||||
??(
|
||||
??(
|
||||
```
|
||||
|
||||
现在可能由于Unicode等字符编码已经普遍存在,不再需要三字母组,而gcc等编译器默认禁用三字母组。
|
||||
233
site_extras/cpp-memory-debug-address-sanitizer-asan.md
Normal file
233
site_extras/cpp-memory-debug-address-sanitizer-asan.md
Normal file
@@ -0,0 +1,233 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-memory-debug/address-sanitizer-asan/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# AddressSanitizer 内存检测
|
||||
|
||||
C和C++是非常不安全且容易出错的编程语言,Address Sanitizer是由Google开发的一种工具,用于检测内存访问错误,如使用后释放(use-after-free)和内存泄漏。它已集成到GCC版本>= 4.8中,可用于C和C++代码。Address Sanitizer使用运行时插桩来跟踪内存分配,这意味着您必须使用AddressSanitizer构建代码,以充分利用其功能。
|
||||
|
||||
- [Use after free](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleUseAfterFree) (dangling pointer dereference)
|
||||
- [Heap buffer overflow](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleHeapOutOfBounds)
|
||||
- [Stack buffer overflow](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleStackOutOfBounds)
|
||||
- [Global buffer overflow](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleGlobalOutOfBounds)
|
||||
- [Use after return](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleUseAfterReturn)
|
||||
- [Use after scope](https://github.com/google/sanitizers/wiki/AddressSanitizerExampleUseAfterScope)
|
||||
- [Initialization order bugs](https://github.com/google/sanitizers/wiki/AddressSanitizerInitializationOrderFiasco)
|
||||
- [Memory leaks](https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer)
|
||||
|
||||
本文将会以上面8种场景来介绍内存检测工具**AddressSanitizer**。
|
||||
|
||||
## 1.Use after free
|
||||
|
||||
以下面代码为例。首先,通过`new`关键字分配了一个整数的内存空间,并将其地址赋给指针 `ptr`。然后,使用 `delete` 关键字释放了这块内存。但是,在释放后,程序仍然尝试通过指针 `ptr` 访问已经释放的内存,并将值 10 赋给该内存位置,这就是使用后释放错误。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
int* ptr = new int;
|
||||
delete ptr;
|
||||
*ptr = 10; // Use after free
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
在编译时添加下面选项。
|
||||
|
||||
```
|
||||
-fsanitize=address
|
||||
```
|
||||
|
||||
运行生成的bin文件,得到如下结果。
|
||||
|
||||

|
||||
|
||||
## 2.heap buffer overflow
|
||||
|
||||
首先,通过 `new` 关键字在堆上分配了一个包含两个整数的数组,并将数组的起始地址赋给指针 `arr`。然后,程序试图将值 10 存储在数组的第三个位置(索引为 2),这超出了数组的有效范围,导致堆缓冲区溢出错误。
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
int* arr = new int[2];
|
||||
arr[2] = 10; // Heap buffer overflow
|
||||
delete[] arr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
同上面用法:
|
||||
|
||||
```
|
||||
g++-13 heap_buffer_overflow.cc -Wall -g -fsanitize=address
|
||||
```
|
||||
|
||||
然后:
|
||||
|
||||
```
|
||||
./a.out
|
||||
```
|
||||
|
||||
得到下面检测结果。
|
||||
|
||||

|
||||
|
||||
## 3.stack buffer overflow
|
||||
|
||||
在 `vulnerableFunction` 函数中,定义了一个包含 8 个字符的字符数组 `buffer`。然后,使用 `std::cin` 从标准输入读取数据存储到 `buffer` 中,但没有限制输入的大小。如果输入的字符数超过了 `buffer` 的大小,就会发生栈缓冲区溢出错误。
|
||||
|
||||
```cpp
|
||||
void vulnerableFunction() {
|
||||
char buffer[8];
|
||||
std::cin >> buffer; // Stack buffer overflow
|
||||
std::cout << "You entered: " << buffer << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
用法同上。
|
||||
|
||||

|
||||
|
||||
## 4.global buffer overflow
|
||||
|
||||
全局缓冲区(`buffer` 数组)在程序的全局范围内定义,而没有受到足够的输入大小限制。如果输入的字符数超过了缓冲区的大小,就会发生全局缓冲区溢出错误。与栈缓冲区溢出类似,全局缓冲区溢出可能导致程序的不稳定性和安全性问题。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
char buffer[8];
|
||||
|
||||
int main() {
|
||||
std::cin >> buffer; // 全局缓冲区溢出错误
|
||||
std::cout << "You entered: " << buffer << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
用法同上,得到:
|
||||
|
||||

|
||||
|
||||
## 5.use after return
|
||||
|
||||
在函数 `f` 中,局部变量 `i` 的地址被返回,但在 `main` 函数中,尝试通过返回的指针访问已经被销毁的局部变量。当出现这种场景是,可以对bin文件进行检测,设置`ASAN_OPTIONS=detect_stack_use_after_return=1`。
|
||||
|
||||
```
|
||||
g++-13 stack_use_after_return.cc -Wall -g -fsanitize=address
|
||||
ASAN_OPTIONS=detect_stack_use_after_return=1 ./a.out
|
||||
```
|
||||
|
||||
代码:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int *f() {
|
||||
int i = 42;
|
||||
int *p = &i;
|
||||
return p;
|
||||
}
|
||||
|
||||
int main() { return *f(); }
|
||||
|
||||
```
|
||||
|
||||
我们便会得到:
|
||||
|
||||

|
||||
|
||||
## 6.use after scope
|
||||
|
||||
将局部变量 `x` 的地址赋给指针 `p`,然而,在超出该内部作用域后,尝试通过指针 `p` 访问已经超出范围的局部变量 `x`,导致范围外使用错误。这也是未定义行为。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
int main() {
|
||||
int* p = 0;
|
||||
{
|
||||
int x = 0;
|
||||
p = &x;
|
||||
}
|
||||
*p = 5;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
编译与运行:
|
||||
|
||||
```
|
||||
g++-13 stack_use_after_scope.cc -Wall -g -fsanitize=address
|
||||
ASAN_OPTIONS=detect_stack_use_after_scope=0 ./a.out
|
||||
```
|
||||
|
||||
实测clang++可以,g++无法检测。
|
||||
|
||||

|
||||
|
||||
## 7.Initialization order bugs
|
||||
|
||||
在两个不同的源文件中,存在全局变量 `a` 的初始化,但初始化的顺序不确定。在 `init_order_b.cc` 文件中,尝试使用变量 `a` 的值,但由于初始化顺序不一致,可能导致未定义的行为。
|
||||
|
||||
代码如下:
|
||||
|
||||
```cpp
|
||||
// init_order_a.cc
|
||||
int duplicate(int n) { return n * 2; }
|
||||
auto a = duplicate(2);
|
||||
|
||||
// init_order_b.cc
|
||||
#include <iostream>
|
||||
|
||||
extern int a;
|
||||
auto b = a;
|
||||
|
||||
int main() {
|
||||
std::cout << b << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
当我们编写这样的代码时,其结果是不确定的,可能是4也可能是0,取决于初始化的顺序。
|
||||
|
||||
例如:
|
||||
|
||||
```
|
||||
clang++ init_order_a.cc init_order_b.cc -Wall -g -fsanitize=address
|
||||
```
|
||||
|
||||
这样输出是4,而先编译b,后编译a,得到0。
|
||||
|
||||
```
|
||||
clang++ init_order_b.cc init_order_a.cc -Wall -g -fsanitize=address
|
||||
```
|
||||
|
||||
当出现这种问题时,我们可以使用AddressSanitizer检测初始化顺序。
|
||||
|
||||
```cpp
|
||||
ASAN_OPTIONS=check_initialization_order=true ./a.out
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 8.memory leak
|
||||
|
||||
通过 `new` 关键字动态分配了一个整数的内存,但在程序结束前未使用 `delete` 关键字释放这块内存,导致内存泄漏。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
int* ptr = new int;
|
||||
// Missing delete ptr; // Memory leak
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
设置`ASAN_OPTIONS=detect_leaks=1`。
|
||||
|
||||
```
|
||||
ASAN_OPTIONS=detect_leaks=1 ./a.out
|
||||
```
|
||||
|
||||

|
||||
133
site_extras/cpp-memory-debug-cpp-memory-leak-detection.md
Normal file
133
site_extras/cpp-memory-debug-cpp-memory-leak-detection.md
Normal file
@@ -0,0 +1,133 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-memory-debug/cpp-memory-leak-detection/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 内存泄漏检测
|
||||
|
||||
## C++那些事之如何检测内存
|
||||
|
||||
我们在编写C/C++代码时,内存问题无处不在,无论是工作还是面试,都离不开内存的话题。
|
||||
|
||||
今天使用一个例子来Step by Step的上手valgrind检测C++内存。
|
||||
|
||||
模拟三个问题:
|
||||
|
||||
- 释放内存问题检测
|
||||
- 写溢出检测
|
||||
- 读溢出检测
|
||||
|
||||
你将会学习到:
|
||||
|
||||
- 如果检测这三个问题
|
||||
- 如果使用gdb + valgrind一起调试
|
||||
|
||||
欢迎一起讨论。
|
||||
|
||||
## 1.示例引入
|
||||
|
||||
大家看一下下面这个代码,我们会发现有很多问题:
|
||||
|
||||
- strcpy不安全,究竟多大的内存大小,可能会越界
|
||||
- print时msg访问越界
|
||||
- 析构函数没有释放内存
|
||||
|
||||
是不是像极了自己曾经写的代码,哈哈。
|
||||
|
||||
本节就来检测出这些问题。
|
||||
|
||||
```cpp
|
||||
class Message {
|
||||
private:
|
||||
char *msg;
|
||||
|
||||
public:
|
||||
Message(const char *text) {
|
||||
msg = new char[3];
|
||||
std::strcpy(msg, text);
|
||||
}
|
||||
|
||||
void printOutOfRange() {
|
||||
std::cout << msg[5] << std::endl;
|
||||
}
|
||||
|
||||
~Message() {
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Message message("hello");
|
||||
message.printOutOfRange();
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 2.valgrind
|
||||
|
||||
valgrind安装:
|
||||
|
||||
```
|
||||
brew install valgrind // mac
|
||||
sudo apt-get install install // ubuntu
|
||||
```
|
||||
|
||||
更多系统的安装参考官方地址:
|
||||
|
||||
> https://valgrind.org/downloads/
|
||||
|
||||
## 3.使用
|
||||
|
||||
首先编译时,建议使用debug,-g,这样的话可以检测到代码哪一行有问题。
|
||||
|
||||
```
|
||||
g++ val_test.cc -g
|
||||
```
|
||||
|
||||
然后我们执行:
|
||||
|
||||
```
|
||||
valgrind --leak-check=full ./a.out
|
||||
```
|
||||
|
||||
我们便得到了valgrind给我们的信息:
|
||||
|
||||

|
||||
|
||||
此时,在上面我们可以看到几个问题:
|
||||
|
||||
- Invalid write
|
||||
|
||||
发生在val_test.cc::11
|
||||
|
||||
- Invalid read
|
||||
|
||||
发生在val_test.cc:10
|
||||
|
||||
- 内存泄漏
|
||||
|
||||
1 allocs, 0 frees,3 bytes allocated.
|
||||
|
||||
这些信息可以快速让我们定位到哪一行代码有问题。
|
||||
|
||||
## 4.gdb调试
|
||||
|
||||
当我们给它加上`--vgdb-error=0`后,我们便可以很方便的调试代码了,一边调试,一边看哪里有问题。
|
||||
|
||||
```cpp
|
||||
valgrind --leak-check=full --vgdb-error=0 ./a.out
|
||||
```
|
||||
|
||||

|
||||
|
||||
随后,我们gdb上去
|
||||
|
||||
```cpp
|
||||
gdb -q a.out
|
||||
```
|
||||
|
||||
把上面的target那一行粘贴到 gdb里面,然后continue,我们便可以看到对应行的代码以及valgrind会继续输出的信息。
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
本节带大家实战内存问题,如果对你有帮助欢迎转发。
|
||||
19
site_extras/cpp-memory-debug-valgrind-massif-memory.md
Normal file
19
site_extras/cpp-memory-debug-valgrind-massif-memory.md
Normal file
@@ -0,0 +1,19 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-memory-debug/valgrind-massif-memory/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Valgrind Massif 内存分析
|
||||
|
||||
gpstart -a --wrapper=valgrind --wrapper-args=" --tool=massif --time-unit=B --detailed-freq=1 --massif-out-file=/tmp/massif.out.%p"
|
||||
|
||||

|
||||
|
||||
```
|
||||
ms_print xxx.out | more
|
||||
```
|
||||
|
||||
https://valgrind.org/docs/manual/ms-manual.html
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
valgrind -v --tool=massif --time-unit=B --detailed-freq=1 --massif-out-file=./massif.out ./a.out
|
||||
7
site_extras/cpp-projects-cpp-fnonce-implementation.md
Normal file
7
site_extras/cpp-projects-cpp-fnonce-implementation.md
Normal file
@@ -0,0 +1,7 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/cpp-fnonce-implementation/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 手撕 C++ FnOnce
|
||||
|
||||
## 《C++那些事》手撕C++版本的Fn、FnOnce、FnMut
|
||||
|
||||
## 1.目标
|
||||
182
site_extras/cpp-projects-cpp-grpc-demo.md
Normal file
182
site_extras/cpp-projects-cpp-grpc-demo.md
Normal file
@@ -0,0 +1,182 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/cpp-grpc-demo/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ gRPC 小项目
|
||||
|
||||
## C++那些事之grpc小Demo
|
||||
|
||||
github上比较火的rpc有grpc、brpc,腾讯内部比较牛逼的trpc等等,这些rpc支持不同的语言、不同平台。今天来聊聊如何使用grpc,从一个简单的demo入手,整个项目使用CMake构建,一个非常标准的rpc项目管理,所有代码已更新至星球,获取方式见最后的二维码。
|
||||
|
||||
## 1.Step by Step 环境
|
||||
|
||||
如果你的电脑是mac,不好意思,暂时用不了最新版本的grpc,最新版本的grpc用了abseil,编译会有问题,官方暂时未解决,如果大家知道如何解决,可以留言,我这边目前未找到解决方法。
|
||||
|
||||
所以,建议安装低版本的grpc在你的mac上,或者在linux直接安装,linux上可以使用最新版本grpc,一次安装没有任何问题。
|
||||
|
||||
安装方式:
|
||||
|
||||
```
|
||||
git clone -b v1.57.0 git@github.com:grpc/grpc.git
|
||||
```
|
||||
|
||||
然后初始化submodule
|
||||
|
||||
```cpp
|
||||
git submodule update --init
|
||||
```
|
||||
|
||||
cmake编译安装:
|
||||
|
||||
```cpp
|
||||
cd cmake
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/grpc ../..
|
||||
|
||||
make -j8
|
||||
make -j8 install // root 权限
|
||||
```
|
||||
|
||||
大家可以修改上面的安装目录,注意install时需要root权限。
|
||||
|
||||
安装完之后,将你的bin目录配置到path,例如:
|
||||
|
||||
```
|
||||
export PATH=/usr/local/grpc/bin:$PATH
|
||||
```
|
||||
|
||||
## 2.反转字符串Demo
|
||||
|
||||
环境搞定了之后,我们便可以上手搞事了。
|
||||
|
||||
### 2.1 协议
|
||||
|
||||
第一件事是确定rpc协议:
|
||||
|
||||
```cpp
|
||||
syntax = "proto3";
|
||||
|
||||
package stringreverse;
|
||||
|
||||
service StringReverse {
|
||||
rpc sendRequest (StringRequest) returns (StringReply) {}
|
||||
}
|
||||
|
||||
message StringRequest {
|
||||
string original = 1;
|
||||
}
|
||||
|
||||
message StringReply {
|
||||
string reversed = 1;
|
||||
}
|
||||
```
|
||||
|
||||
非常简单的协议,请求一个字符串,返回一个字符串。
|
||||
|
||||
### 2.2 客户端
|
||||
|
||||
构造rpc请求字符串,然后调用sendRequest接口发送出去即可。
|
||||
|
||||
```cpp
|
||||
std::string str = "hello world grpc!";
|
||||
std::cout << "Original string: " << str << std::endl;
|
||||
StringRequest request;
|
||||
StringReply reply;
|
||||
ClientContext context;
|
||||
request.set_original(str);
|
||||
Status status = stub->sendRequest(&context, request, &reply);
|
||||
if (status.ok()) {
|
||||
std::cout << "Reversed string: " << reply.reversed() << std::endl;
|
||||
}
|
||||
// do something
|
||||
```
|
||||
|
||||
### 2.3 服务端
|
||||
|
||||
通过继承Service实现反转字符串逻辑。
|
||||
|
||||
```cpp
|
||||
class ReverseServiceImplementation final : public StringReverse::Service {
|
||||
Status sendRequest(ServerContext* context, const StringRequest* request,
|
||||
StringReply* reply) override {
|
||||
// 反转逻辑
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
最后注册service即可:
|
||||
|
||||
```cpp
|
||||
builder.RegisterService(&service);
|
||||
std::unique_ptr<Server> server(builder.BuildAndStart());
|
||||
std::cout << "Server listening on port: " << server_address << std::endl;
|
||||
```
|
||||
|
||||
## 3.运行
|
||||
|
||||
创建编译目录:
|
||||
|
||||
```
|
||||
mkdir build
|
||||
cmake ..
|
||||
# 输出
|
||||
-- The C compiler identification is GNU 10.2.1
|
||||
-- The CXX compiler identification is GNU 10.2.1
|
||||
-- Detecting C compiler ABI info
|
||||
-- Detecting C compiler ABI info - done
|
||||
-- Check for working C compiler: /opt/rh/devtoolset-10/root/usr/bin/cc - skipped
|
||||
-- Detecting C compile features
|
||||
-- Detecting C compile features - done
|
||||
-- Detecting CXX compiler ABI info
|
||||
-- Detecting CXX compiler ABI info - done
|
||||
-- Check for working CXX compiler: /opt/rh/devtoolset-10/root/usr/bin/c++ - skipped
|
||||
-- Detecting CXX compile features
|
||||
-- Detecting CXX compile features - done
|
||||
-- Looking for pthread.h
|
||||
-- Looking for pthread.h - found
|
||||
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
|
||||
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
|
||||
-- Looking for pthread_create in pthreads
|
||||
-- Looking for pthread_create in pthreads - not found
|
||||
-- Looking for pthread_create in pthread
|
||||
-- Looking for pthread_create in pthread - found
|
||||
-- Found Threads: TRUE
|
||||
-- Found Protobuf: /usr/local/grpc/bin/protoc-23.4.0 (found version "23.4.0")
|
||||
-- Using protobuf
|
||||
-- Using gRPC 1.57.0
|
||||
-- Configuring done
|
||||
-- Generating done
|
||||
-- Build files have been written to: /code/stringreverse/build
|
||||
```
|
||||
|
||||
make编译:
|
||||
|
||||
```
|
||||
[ 10%] Generating stringreverse.pb.cc, stringreverse.pb.h, stringreverse.grpc.pb.cc, stringreverse.grpc.pb.h
|
||||
Scanning dependencies of target server
|
||||
[ 20%] Building CXX object CMakeFiles/server.dir/server.cc.o
|
||||
[ 30%] Building CXX object CMakeFiles/server.dir/stringreverse.pb.cc.o
|
||||
[ 40%] Building CXX object CMakeFiles/server.dir/stringreverse.grpc.pb.cc.o
|
||||
[ 50%] Linking CXX executable server
|
||||
[ 50%] Built target server
|
||||
Scanning dependencies of target client
|
||||
[ 60%] Building CXX object CMakeFiles/client.dir/client.cc.o
|
||||
[ 70%] Building CXX object CMakeFiles/client.dir/stringreverse.pb.cc.o
|
||||
[ 80%] Building CXX object CMakeFiles/client.dir/stringreverse.grpc.pb.cc.o
|
||||
[ 90%] Linking CXX executable client
|
||||
[100%] Built target client
|
||||
```
|
||||
|
||||
运行server:
|
||||
|
||||
```
|
||||
[light@i-i339drlk build]$ ./server
|
||||
Server listening on port: 0.0.0.0:5000
|
||||
```
|
||||
|
||||
运行client:
|
||||
|
||||
```cpp
|
||||
[light@i-i339drlk build]$ ./client
|
||||
Original string: hello world grpc!
|
||||
Reversed string: !cprg dlrow olleh
|
||||
```
|
||||
83
site_extras/cpp-projects-cpp-ipc-practice.md
Normal file
83
site_extras/cpp-projects-cpp-ipc-practice.md
Normal file
@@ -0,0 +1,83 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/cpp-ipc-practice/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 进程间通信实战
|
||||
|
||||
进程间通信是一个非常重要的话题,特别是像一些大型项目都有它的影子,例如:PostgreSQL使用了管道完成copy的进程间通信,那么本节也将基于这个主题,使用C++去搭建一个进程间通过管道通信的demo出来,本节将会结合前面几节讲的内容,给出一个比较完整的实战例子出来:
|
||||
|
||||
- mutex
|
||||
- condition_variable
|
||||
- thread
|
||||
|
||||
注:本节的完整代码会放在星球中。
|
||||
|
||||
首先一个很简单的管道用法为:
|
||||
|
||||
- 创建一个管道
|
||||
|
||||
它会creating a pipe, forking, and invoking the shell.
|
||||
|
||||
```cpp
|
||||
// FILE *popen(const char *command, const char *type);
|
||||
pipe = popen(command.c_str(), "w");
|
||||
```
|
||||
|
||||
- 关闭一个管道
|
||||
|
||||
```cpp
|
||||
// int pclose(FILE *stream);
|
||||
pclose(pipe);
|
||||
```
|
||||
|
||||
接下来我们就只需要往里面写与读了,原理也很简单,例如:
|
||||
|
||||
此时便会把data写入到前面创建的管道中。
|
||||
|
||||
```cpp
|
||||
// size_t fwrite( const void* buffer, size_t size, size_t count, FILE* stream );
|
||||
size_t written = fwrite(data.c_str(), sizeof(char), data.size(), pipe);
|
||||
```
|
||||
|
||||
如果从管道中读取,我们可以使用fread或者fgets,`fgets` 会在读取到换行符或达到缓冲区大小时停止,而 `fread` 会尽可能多地读取数据,直到达到指定的字节数或遇到文件结尾。同理,上面的fwrite可以替换为fputs。
|
||||
|
||||
现在,一个管道的基本使用介绍完了,如何写一个完整的demo?
|
||||
|
||||
很简单,我们只需要创建两个线程,一个读,一个写,然后写线程往pipe里面写数据,读线程从pipe里面读即可。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
std::thread writer_thread(write_to_pipe);
|
||||
std::thread reader_thread(read_from_pipe);
|
||||
|
||||
writer_thread.join();
|
||||
reader_thread.join();
|
||||
```
|
||||
|
||||
写线程需要做的事情就是调用fwrite丢数据即可
|
||||
|
||||
```cpp
|
||||
ProcessWriter writer("cat > /tmp/pipe");
|
||||
|
||||
// 写入数据
|
||||
std::string message = "Hello pipe!\n";
|
||||
if (!writer.write(message)) {
|
||||
std::cerr << "Failed to write data to pipe" << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
同理,读线程取数据:
|
||||
|
||||
```cpp
|
||||
ProcessReader reader("/tmp/pipe");
|
||||
// 读取数据
|
||||
std::string message;
|
||||
while (reader.read(message)) {
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
最后的效果就是:
|
||||
|
||||
```cpp
|
||||
Read from pipe: Hello pipe!
|
||||
```
|
||||
70
site_extras/cpp-projects-cpp-short-url-demo.md
Normal file
70
site_extras/cpp-projects-cpp-short-url-demo.md
Normal file
@@ -0,0 +1,70 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/cpp-short-url-demo/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 短链接服务 Demo
|
||||
|
||||
真实的短链接相对来说比较复杂,例如:hash算法、放号系统等等。
|
||||
|
||||
今天只是从小项目角度模拟一个短链接实现。
|
||||
|
||||
如何通过短短的几十行代码快速实现一个?其中涉及的几个关键点:
|
||||
|
||||
- 如何将长链接缩短
|
||||
- 如何存储映射关系
|
||||
|
||||
映射关系就不用说了,整一个map持久化内存,如果涉及到数据库,需要通过数据库的jdbc/odbc等接口访问写入库当中。
|
||||
|
||||
长链接缩短这里采用随机算法+固定长度思路来实现。
|
||||
|
||||
## 1.随机
|
||||
|
||||
通过uniform_int_distribution,生成一个`[a, b]`区间的随机数,这里随机从下列字符串中每次取一个字符,最后拼接起来就是短链接。
|
||||
|
||||
```cpp
|
||||
string characters{
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
|
||||
```
|
||||
|
||||
包含:
|
||||
|
||||
- 数字
|
||||
- 小写字母
|
||||
- 大写字母
|
||||
|
||||
```cpp
|
||||
uniform_int_distribution<int> distribution(0, characters.size() - 1);
|
||||
string code;
|
||||
for (int i = 0; i < length; ++i)
|
||||
code += characters[distribution(generator)];
|
||||
```
|
||||
|
||||
## 2.存储
|
||||
|
||||
每次将其存储到map中即可,例如:
|
||||
|
||||
```cpp
|
||||
if (links.count(originalLink)) {
|
||||
return links[originalLink];
|
||||
}
|
||||
|
||||
shortCode = generateRandomCode(len);
|
||||
string shortenedLink = base_url + shortCode;
|
||||
links[shortenedLink] = originalLink;
|
||||
```
|
||||
|
||||
这里保留了基本url,例如:
|
||||
|
||||
```cpp
|
||||
string baseUrl = "https://www.google.com.hk/search";
|
||||
LinkShortener shortener(baseUrl);
|
||||
|
||||
string originalLink = "https://www.google.com.hk/search?q=asdsad&oq=asdsad&aqs=chrome.0.69i59j69i57j69i59l2.634j0j4&sourceid=chrome&ie=UTF-8";
|
||||
string shortenedLink = shortener.shortenLink(originalLink, 8);
|
||||
```
|
||||
|
||||
最后便可以将这个url缩短为:
|
||||
|
||||
```
|
||||
https://www.google.com.hk/searchtXuOlOSt
|
||||
```
|
||||
|
||||
是不是很简单,本节的测试与完整代码已在星球更新,欢迎加入一起学习成长~
|
||||
134
site_extras/cpp-projects-cpp17-sqlite-folder-size.md
Normal file
134
site_extras/cpp-projects-cpp17-sqlite-folder-size.md
Normal file
@@ -0,0 +1,134 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/cpp17-sqlite-folder-size/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 与 SQLite 统计目录大小
|
||||
|
||||
## 项目实战:使用 C++17 和 SQLite 实现文件夹大小计算与存储
|
||||
|
||||
[TOC]
|
||||
|
||||
本节将会围绕一个项目背景展开:假设业务中需要定时检查某些文件夹大小,并做一下持久化操作,C++如何去完成这一个项目呢?
|
||||
|
||||
本节带你通过一个小项目,使用 C++17 和 SQLite 实现一个文件夹大小计算与存储的系统,帮助你更好地管理你的文件系统。
|
||||
|
||||
### 项目目标
|
||||
|
||||
我们将实现以下功能:
|
||||
1. **递归计算指定目录及其子目录的大小**。
|
||||
2. **将计算结果保存到 SQLite 数据库**,方便后续查询和分析。
|
||||
3. **可扩展性强**:你可以轻松修改项目,添加多线程支持、优化性能,或将结果存储到其他数据库中。
|
||||
|
||||
**注:懒人版,完整代码已更新星球。**
|
||||
|
||||
### 项目实现步骤
|
||||
|
||||
#### 1. 环境
|
||||
|
||||
首先,你需要确保开发环境中已经安装了以下工具:
|
||||
- **支持C++17 编译器**:如 g++,通过以下命令可以检查版本:
|
||||
|
||||
```bash
|
||||
g++ --version
|
||||
```
|
||||
确保 g++ 支持 C++17 标准。
|
||||
|
||||
- **SQLite3**:数据库操作我们会使用 SQLite,你可以通过包管理器来安装它:
|
||||
```bash
|
||||
sudo apt-get install sqlite3 libsqlite3-dev
|
||||
```
|
||||
安装完后,SQLite 数据库的开发库 `libsqlite3-dev` 可以确保我们在 C++ 中能正常使用 SQLite。
|
||||
|
||||
#### 2. 创建项目结构
|
||||
|
||||
我们将把代码分为多个模块,保持清晰的架构:
|
||||
- `folder_size.h` / `folder_size.cpp`:负责递归计算目录及其子目录大小。
|
||||
- `database.h` / `database.cpp`:封装 SQLite 数据库操作逻辑。
|
||||
- `main.cpp`:主程序入口,负责整体流程的控制。
|
||||
|
||||
项目的目录结构如下:
|
||||
```
|
||||
project/
|
||||
│── folder_size.h
|
||||
│── folder_size.cpp
|
||||
│── database.h
|
||||
│── database.cpp
|
||||
└── main.cpp
|
||||
```
|
||||
|
||||
#### 3. 代码实现
|
||||
|
||||
接下来,我们将一步步实现每个模块。
|
||||
|
||||
##### 3.1 目录计算模块
|
||||
|
||||
C++17 提供了`std::filesystem` 库来递归遍历目录并计算大小。因此其核心实现如下:
|
||||
|
||||
```cpp
|
||||
uintmax_t total_size = 0;
|
||||
for (const auto& entry : fs::recursive_directory_iterator(dir_path)) {
|
||||
if (fs::is_regular_file(entry.path())) {
|
||||
total_size += fs::file_size(entry.path());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
如果要计算根目录 再计算一次即可。
|
||||
|
||||
##### 3.2 SQLite数据库操作
|
||||
|
||||
引入:
|
||||
|
||||
```
|
||||
#include <sqlite3.h>
|
||||
```
|
||||
|
||||
使用:
|
||||
|
||||
```cpp
|
||||
sqlite3_close(db_); // 关闭
|
||||
|
||||
// 插入
|
||||
for (const auto& [folder, size] : folder_sizes) {
|
||||
const std::string insert_sql =
|
||||
"INSERT OR REPLACE INTO FolderSizes (Folder, Size) "
|
||||
"VALUES ('" + folder + "', " + std::to_string(size) + ");";
|
||||
if (!ExecuteSQL(insert_sql)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行
|
||||
sqlite3_exec
|
||||
```
|
||||
|
||||
#### 4. 编译与运行
|
||||
|
||||
编译项目非常简单:
|
||||
|
||||
```bash
|
||||
mkdir build
|
||||
cmake ../
|
||||
make -j8
|
||||
```
|
||||
|
||||
然后,运行程序,计算目录大小并存储到数据库:
|
||||
|
||||
```bash
|
||||
./folder_size_calculator
|
||||
```
|
||||
|
||||
程序将会递归计算指定目录的大小,并将结果保存到 `folder_sizes.db` 数据库中。
|
||||
|
||||
#### 5. 查询数据库
|
||||
|
||||
最后,你可以通过
|
||||
|
||||
SQLite 命令行工具查询数据库中的内容:
|
||||
|
||||
```bash
|
||||
sqlite3 folder_sizes.db
|
||||
sqlite> SELECT * FROM FolderSizes;
|
||||
```
|
||||
|
||||
这将显示所有已保存的目录及其对应的大小。
|
||||
|
||||
> 本节完
|
||||
109
site_extras/cpp-projects-google-benchmark-cpp.md
Normal file
109
site_extras/cpp-projects-google-benchmark-cpp.md
Normal file
@@ -0,0 +1,109 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/google-benchmark-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Google Benchmark 性能测试
|
||||
|
||||
## 《C++那些事》之开启你的BenchMark测试
|
||||
|
||||
## 0.导语
|
||||
|
||||
本节目标:完成一个BenchMark小项目!
|
||||
|
||||
在平时开发中,如何测试自己的接口性能呢?C++里面如何快速搭建一个BenchMark测试框架呢?
|
||||
|
||||
本节将Step By Step开启BenchMark入门的第一课。
|
||||
|
||||
## 1.项目结构
|
||||
|
||||
我们以vector与list插入为例,来讲解BenchMark项目。
|
||||
|
||||
这次项目是基于Bazel来管理的,如果还不知道如何配置相关环境的,请参考之前的视频课程/文档资料。
|
||||
|
||||
创建一个项目结构为:
|
||||
|
||||
```
|
||||
```
|
||||
|
||||
BenchMark采用google的开源项目:
|
||||
|
||||
```cpp
|
||||
https://github.com/google/benchmark.git
|
||||
```
|
||||
|
||||
像以前大家使用第三方库,需要自己源码编译一波,生成so库,然后链接,太麻烦了!这里直接使用bazel管理,只需要在WORKSPACE里面,添加依赖的git项目,例如这里采用google benchmark的v1.7.1版本。
|
||||
|
||||
```cpp
|
||||
git_repository(
|
||||
name = "google_benchmark",
|
||||
remote = "https://github.com/google/benchmark.git",
|
||||
tag = "v1.7.1",
|
||||
)
|
||||
```
|
||||
|
||||
随后,我们需要实现主逻辑,创建一个src目录,里面添加一个BUILD文件:目的在于编译过会cpp文件,注意:这里依赖了benchmark库,使用方法为@**前面配置的name**//:benchmark
|
||||
|
||||
```cpp
|
||||
cc_binary(
|
||||
name = "vector_list",
|
||||
srcs = ["vector_list.cc"],
|
||||
deps = [
|
||||
"@google_benchmark//:benchmark",
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
这样的话,在cc文件中便可以使用了:
|
||||
|
||||
```cpp
|
||||
#include <benchmark/benchmark.h>
|
||||
```
|
||||
|
||||
### 2.Demo环节
|
||||
|
||||
编写两个插入函数,非常简单,框架如下所示,里面有一些需要说明的,如下:
|
||||
|
||||
- state为benchmark的运行时状态信息
|
||||
- 例如:休眠控制、入参数控制等
|
||||
- state.range(0)便是获取第0个参数
|
||||
- DoNotOptimize表示不做编译器优化
|
||||
|
||||
```cpp
|
||||
// 测试 std::vector 的插入速度
|
||||
static void BM_vectorInsert(benchmark::State& state) {
|
||||
for (auto _ : state) {
|
||||
std::vector<int> v;
|
||||
for (size_t i = 0; i < state.range(0); ++i) {
|
||||
v.insert(v.begin() + i, i);
|
||||
}
|
||||
benchmark::DoNotOptimize(v);
|
||||
}
|
||||
}
|
||||
|
||||
// 测试 std::list 的插入速度
|
||||
static void BM_listInsert(benchmark::State& state) {
|
||||
for (auto _ : state) {
|
||||
std::list<int> l;
|
||||
for (size_t i = 0; i < state.range(0); ++i) {
|
||||
l.insert(l.begin(), i);
|
||||
}
|
||||
benchmark::DoNotOptimize(l);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
主入口调用:
|
||||
|
||||
- Range(8, 8 << 10) 表示从8开始,每次乘以8,直到8192,这个对应上面的state.range(0),会把这个数作为参数传递进去
|
||||
- BENCHMARK_MAIN表示使用google benchmark的main函数,我们知道每个可执行文件都有一个main,那这个文件可以执行的原因就在于,这个宏展开后就是main函数,你学会了吗?
|
||||
|
||||
```cpp
|
||||
// 定义基准测试
|
||||
BENCHMARK(BM_vectorInsert)->Range(8, 8<<10);
|
||||
BENCHMARK(BM_listInsert)->Range(8, 8<<10);
|
||||
|
||||
// 运行基准测试
|
||||
BENCHMARK_MAIN();
|
||||
```
|
||||
|
||||
## 3.总结
|
||||
|
||||
本节Step by Step带大家学习google benchmark,并将其应用到我们自己的项目中,你可以在里面做很多有趣的事情,本节源码放入知识星球当中供大家学习,欢迎加入一起交流~
|
||||
37
site_extras/cpp-projects-modern-cpp-http-server.md
Normal file
37
site_extras/cpp-projects-modern-cpp-http-server.md
Normal file
@@ -0,0 +1,37 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/modern-cpp-http-server/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 协程 HTTP 服务器
|
||||
|
||||
## 现代 C++ HTTP 服务器
|
||||
|
||||
最近星球小伙伴总是问我有没有网络相关的项目,于是写了一个基于现代C++ + CMake管理的完整项目。
|
||||
|
||||
该项目具备以下特性:
|
||||
|
||||
- 大量现代C++特性
|
||||
- C++20相关
|
||||
- cortouine
|
||||
- concept
|
||||
- std::format
|
||||
- std::span
|
||||
- C++17相关
|
||||
- if语句初始化
|
||||
- 结构化绑定
|
||||
- optional
|
||||
- 高效的事件驱动机制
|
||||
- 使用 `epoll` 实现事件循环,管理大量的客户端连接。`epoll` 是 Linux 平台上处理高并发 I/O 的高效工具,它可以同时监听多个文件描述符的事件,从而有效地减少系统调用开销,提高 I/O 操作的并发性。
|
||||
- 服务器在主事件循环中通过非阻塞 `epoll_wait` 监听连接事件,避免了传统阻塞 I/O 带来的性能瓶颈。
|
||||
- 协程与异步编程
|
||||
- 采用 C++20 协程简化异步任务的实现,提供了类似同步代码的写法,使代码逻辑更加清晰。项目中通过 `co_await` 异步读取和写入客户端数据,减少了线程上下文切换的开销。
|
||||
- 实现了 `SocketAwaiter` 和 `AsyncSocketOperation` 两个类,用于封装套接字的异步读写操作,使得编写异步处理代码变得更加简洁和自然。
|
||||
- 文件 I/O 操作的异步处理
|
||||
- 服务器支持异步读取 HTML 文件内容,通过 `std::async` 实现异步文件读取,避免阻塞主线程,从而更快地响应客户端请求。
|
||||
- 在处理请求时,异步读取所需的文件并缓存到内存,减少了 I/O 操作对性能的影响。
|
||||
- 非阻塞套接字操作
|
||||
- 使用 `fcntl` 将套接字设置为非阻塞模式,保证 `accept` 和 `read/write` 操作不会阻塞服务器的主线程。这在高并发场景下尤为重要,可以显著提高服务器的并发处理能力。
|
||||
|
||||
项目效果:
|
||||
|
||||
|
||||
|
||||
学习方式:有详细的文档+代码,可以单独购买加下方微信或者加入星球即可。
|
||||
180
site_extras/cpp-projects-protobuf-zerocopy-cpp.md
Normal file
180
site_extras/cpp-projects-protobuf-zerocopy-cpp.md
Normal file
@@ -0,0 +1,180 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/protobuf-zerocopy-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Protobuf ZeroCopy 序列化
|
||||
|
||||
## 1.ZeroCopyStream
|
||||
|
||||
protobuf在io接口上有一个叫做ZeroCopyStream,对于IO的接口设计,pb提供了相关序列化与反序列化接口,如:
|
||||
|
||||
```cpp
|
||||
// Read a protocol buffer from the given zero-copy input stream. If
|
||||
// successful, the entire input will be consumed.
|
||||
bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input);
|
||||
|
||||
// Write the message to the given zero-copy output stream. All required
|
||||
// fields must be set.
|
||||
bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
|
||||
```
|
||||
|
||||
ZeroCopyStream设计的初衷是最小化buffer的拷贝次数,即省略掉stream内部数据拷贝到用户buffer。因此,stream可以返回一个缓冲区,该缓冲区实际上直接指向要存储字节的最终数据结构,并且调用者可以直接与该缓冲区交互,从而消除了中间复制操作。
|
||||
|
||||
例如:经典的IO stream:
|
||||
|
||||
```cpp
|
||||
char buffer[[]BUFFER_SIZE];
|
||||
input->Read(buffer, BUFFER_SIZE);
|
||||
DoSomething(buffer, BUFFER_SIZE);
|
||||
```
|
||||
|
||||
然后,stream基本上只是调用memcpy()将数据从pb复制到用户buffer中。如果使用ZeroCopyInputStream,我们只需要:
|
||||
|
||||
```cpp
|
||||
const void* buffer;
|
||||
int size;
|
||||
input->Next(&buffer, &size);
|
||||
DoSomething(buffer, size);
|
||||
```
|
||||
|
||||
这里不执行拷贝,调用者最终直接从buffer中读取。
|
||||
|
||||
ZeroCopyStream提供了两个基类:ZeroCopyOutputStream/ZeroCopyInputStream。
|
||||
|
||||
以InputStream为例,通常我们可以通过继承的方式自定义自己的ZerCopyStream,需要实现下面四个接口。
|
||||
|
||||
```cpp
|
||||
// implements ZeroCopyInputStream ----------------------------------
|
||||
bool Next(const void** data, int* size);
|
||||
void BackUp(int count);
|
||||
bool Skip(int count);
|
||||
int64 ByteCount() const;
|
||||
```
|
||||
|
||||
一些rpc框架基本都自定义自己的Stream,例如:sofa-pbrpc
|
||||
|
||||
> https://github.com/baidu/sofa-pbrpc/blob/master/src/sofa/pbrpc/buffer.h
|
||||
|
||||
## 2.Demo
|
||||
|
||||
定义一个pb协议,例如:授权验证:
|
||||
|
||||
```cpp
|
||||
syntax = "proto3";
|
||||
|
||||
message BasicAuth {
|
||||
string username = 1;
|
||||
string password = 2;
|
||||
}
|
||||
```
|
||||
|
||||
随后编写序列化与反序列化:
|
||||
|
||||
- 序列化
|
||||
|
||||
```cpp
|
||||
BasicAuth auth_message;
|
||||
auth_message.set_username("user123");
|
||||
auth_message.set_password("password");
|
||||
|
||||
StringOutputStream output_stream(&buf);
|
||||
|
||||
auth_message.SerializeToZeroCopyStream(&output_stream);
|
||||
```
|
||||
|
||||
- 反序列化
|
||||
|
||||
```cpp
|
||||
ArrayInputStream input_stream(buf.data(), buf.size());
|
||||
BasicAuth auth_message;
|
||||
if (!auth_message.ParseFromZeroCopyStream(&input_stream)) {
|
||||
std::cerr << "Failed to parse data." << std::endl;
|
||||
}
|
||||
|
||||
std::cout << "Username: " << auth_message.username() << std::endl;
|
||||
std::cout << "Password: " << auth_message.password() << std::endl;
|
||||
```
|
||||
|
||||
随后我们便可以调用它:
|
||||
|
||||
```cpp
|
||||
int main() {
|
||||
std::string buf;
|
||||
buf.reserve(512);
|
||||
ser(buf);
|
||||
deser(buf);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
Username: user123
|
||||
Password: password
|
||||
```
|
||||
|
||||
本节完,以上完整代码见知识星球,欢迎与我共同探讨rpc相关内容。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
(gdb) p *dsr
|
||||
$8 = {typeInfo = {datumlen = 4, typid = 1082, align = 105 'i', byval = true}, datumStreamVersion = DatumStreamVersion_Original, nth = -1,
|
||||
logical_row_count = 16382, datump = 0x3840470 "\277\377\377\377\231\002", physical_datum_index = -1, physical_datum_count = 0,
|
||||
datum_beginp = 0x3840470 "\277\377\377\377\231\002", datum_afterp = 0x38503dc "", has_null = true, buffer_beginp = 0x383fc60 "",
|
||||
null_bitmap = {buffer = 0x383fc70 "", byteBit = 0 '\000', bytePointer = 0x383fc70 "", bitCount = 16382, bitPosition = -1,
|
||||
readBitOnCount = 58981488}, null_bitmap_beginp = 0x0, rle_can_have_compression = false, rle_compress_beginp = 0x0, rle_repeatcountsp = 0x0,
|
||||
delta_beginp = 0x0, delta_deltasp = 0x0, delta_datum_p = 0, rle_norepeats_null_bitmap_count = 0, rle_compress_bitmap_count = 0,
|
||||
rle_repeatcounts_count = 0, rle_repeatcounts_size = 0, delta_item = false, delta_bitmap_count = 0, deltas_count = 0, deltas_size = 0,
|
||||
rle_block_was_compressed = false, rle_compress_bitmap = {buffer = 0x0, byteBit = 0 '\000', bytePointer = 0x0, bitCount = 0, bitPosition = 0,
|
||||
readBitOnCount = 0}, rle_repeatcounts_index = 0, rle_in_repeated_item = false, rle_repeated_item_count = 0,
|
||||
rle_total_repeat_items_read = 0, delta_block_was_compressed = false, delta_bitmap = {buffer = 0x0, byteBit = 0 '\000',
|
||||
bytePointer = 0xff6c00454244 <error: Cannot access memory at address 0xff6c00454244>, bitCount = 0, bitPosition = 0,
|
||||
readBitOnCount = 13651600}, eyecatcher = "\000\000\000", physical_data_size = 0, maxDataBlockSize = 13652112,
|
||||
errdetailCallback = 0x35daeb0, errdetailArg = 0x34c4e18, errcontextCallback = 0x34c4e18, errcontextArg = 0x383fc60, memctxt = 0x1077c}
|
||||
```
|
||||
157
site_extras/cpp-projects-pybind11-python-cpp.md
Normal file
157
site_extras/cpp-projects-pybind11-python-cpp.md
Normal file
@@ -0,0 +1,157 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/pybind11-python-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# pybind11 加速 Python
|
||||
|
||||
通常像一些耗时的操作,我们期望在C++中去实现,然后使用Python去调用对应的接口,或者因为底层库的原因,需要支持对外的Python API,那么我们通常需要支持在Python中访问C++,如何实现呢?
|
||||
|
||||
方法比较多,本节以pybind11为例,引入一个完整的项目工程模版,如果你后续有这种需求,可以基于模版去修改。
|
||||
|
||||
注:(懒人版)本节的所有代码也都放在星球里面。
|
||||
|
||||
## 1.宏展开
|
||||
|
||||
假设:我们以比较耗时的排序为例,如果我们想在C++中写一个排序,然后在Python中去使用它,怎么去写呢?
|
||||
|
||||
C++程序是比较简单的,对外暴露一个接口里面做排序即可,例如:
|
||||
|
||||
```cpp
|
||||
std::vector<int> sort_vector(const std::vector<int>& input) {
|
||||
std::vector<int> result = input;
|
||||
std::sort(result.begin(), result.end());
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
那么问题来了,对于Pybind11来说,如何使用这个接口呢?
|
||||
|
||||
使用pybind11的宏即可定义一个模块,例如:
|
||||
|
||||
```cpp
|
||||
PYBIND11_MODULE(sort_module, m) {
|
||||
m.doc() = "pybind11 example plugin"; // Optional module docstring
|
||||
|
||||
m.def("sort_vector", &sort_vector, "A function that sorts a list of integers");
|
||||
}
|
||||
```
|
||||
|
||||
宏展开之后是:PyInit_sort_module
|
||||
|
||||
当我们在python当中import xxx库的时候,Python 解释器会去加载一个 C/C++ 编写的扩展模块时自动调用的入口函数,而这个入口函数就是下面的PyInit_sort_module:
|
||||
|
||||
```cpp
|
||||
static ::pybind11::module_::module_def pybind11_module_def_sort_module [[maybe_unused]];
|
||||
|
||||
[[maybe_unused]] static void pybind11_init_sort_module(::pybind11::module_ &);
|
||||
|
||||
extern "C" [[maybe_unused]] __attribute__((visibility("default"))) PyObject *PyInit_sort_module();
|
||||
|
||||
extern "C" __attribute__((visibility("default"))) PyObject *PyInit_sort_module() {
|
||||
{
|
||||
const char *compiled_ver = "3" "." "11";
|
||||
const char *runtime_ver = Py_GetVersion();
|
||||
size_t len = std::strlen(compiled_ver);
|
||||
|
||||
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {
|
||||
PyErr_Format(PyExc_ImportError,
|
||||
"Python version mismatch: module was compiled for Python %s, "
|
||||
"but the interpreter version is incompatible: %s.",
|
||||
compiled_ver, runtime_ver);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
pybind11::detail::get_internals();
|
||||
auto m = ::pybind11::module_::create_extension_module("sort_module", nullptr, &pybind11_module_def_sort_module);
|
||||
|
||||
try {
|
||||
pybind11_init_sort_module(m);
|
||||
return m.ptr();
|
||||
} catch (pybind11::error_already_set & e) {
|
||||
pybind11::raise_from(e, PyExc_ImportError, "initialization failed");
|
||||
return nullptr;
|
||||
} catch (const std::exception &e) {
|
||||
::pybind11::set_error(PyExc_ImportError, e.what());
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void pybind11_init_sort_module(::pybind11::module_ & m) {
|
||||
m.doc() = "pybind11 example plugin";
|
||||
|
||||
m.def("sort_vector", &sort_vector, "A function that sorts a list of integers");
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
所以,如果我们不去使用这个宏,在import库的时候会报错:
|
||||
|
||||
```python
|
||||
>>> import sort_module
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ImportError: dynamic module does not define module export function (PyInit_sort_module)
|
||||
```
|
||||
|
||||
## 2.CMake + pybind11
|
||||
|
||||
pybind11在C++中的使用如下:
|
||||
|
||||
- 头文件
|
||||
|
||||
```cpp
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
```
|
||||
|
||||
- 宏
|
||||
|
||||
```
|
||||
PYBIND11_MODULE(sort_module, m) {
|
||||
// 你的实现
|
||||
}
|
||||
```
|
||||
|
||||
那么如何在cmake中下载并链接pybind11呢?
|
||||
|
||||
只需要使用FetchContent模块即可,例如:
|
||||
|
||||
```cpp
|
||||
FetchContent_Declare(
|
||||
pybind11
|
||||
URL https://github.com/pybind/pybind11/archive/v2.12.0.tar.gz
|
||||
)
|
||||
```
|
||||
|
||||
然后在CMakeLists中加入你的模块即可:
|
||||
|
||||
```cpp
|
||||
pybind11_add_module(sort_module sort_module.cc)
|
||||
```
|
||||
|
||||
cmake将会帮你下载pybingd11,同时编译好。
|
||||
|
||||
## 3.使用
|
||||
|
||||
上面会生成一个so,install到python的site-packages目录,然后import的时候便会识别,如下演示我们自定义的模块:
|
||||
|
||||
```python
|
||||
import sort_module
|
||||
|
||||
def test_sort():
|
||||
input_list = [5, 2, 3, 1, 4]
|
||||
sorted_list = sort_module.sort_vector(input_list)
|
||||
print(f"Original list: {input_list}")
|
||||
print(f"Sorted list: {sorted_list}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_sort()
|
||||
|
||||
```
|
||||
|
||||
运行:
|
||||
|
||||
```
|
||||
(base) ➜ build python ../test.py
|
||||
Original list: [5, 2, 3, 1, 4]
|
||||
Sorted list: [1, 2, 3, 4, 5]
|
||||
```
|
||||
75
site_extras/cpp-projects-stack-calculator-design.md
Normal file
75
site_extras/cpp-projects-stack-calculator-design.md
Normal file
@@ -0,0 +1,75 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/stack-calculator-design/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 栈式计算器设计
|
||||
|
||||
写一个栈计算器,设计如下:
|
||||
|
||||
- 支持 `+`、`-`、`*`、`/`运算
|
||||
- 支持后缀输入
|
||||
|
||||
例如:
|
||||
```
|
||||
2 3 +
|
||||
```
|
||||
输出:
|
||||
```
|
||||
5
|
||||
```
|
||||
如何实现呢?
|
||||
|
||||
其中最关键两个问题:
|
||||
|
||||
1.如何分词
|
||||
|
||||
2.如何实现栈
|
||||
|
||||
## 1.如何分词
|
||||
|
||||
首先定义好输入是一个字符串,空格风格,我们便可以使用istringstream分割每一个token了,基本框架为:
|
||||
|
||||
```cpp
|
||||
std::istringstream iss(expression);
|
||||
std::string token;
|
||||
while (iss >> token) {
|
||||
}
|
||||
```
|
||||
|
||||
## 2.如何实现栈
|
||||
|
||||
对于计算器来说,最核心就是入栈、出栈。
|
||||
|
||||
- 碰到数字入栈
|
||||
- 碰到操作符出栈计算
|
||||
|
||||
我们便可以写出框架:
|
||||
|
||||
```cpp
|
||||
if (isNumber(token)) {
|
||||
pushNumber(token);
|
||||
} else if (isOperator(token)) {
|
||||
popAndCal(token);
|
||||
} else {
|
||||
throw std::runtime_error("Invalid token in expression.");
|
||||
}
|
||||
```
|
||||
|
||||
popAndCal是计算的核心,如:
|
||||
|
||||
```cpp
|
||||
void popAndCal(const std::string& token) {
|
||||
if (operandStack.size() < 2) {
|
||||
throw std::runtime_error("Invalid expression.");
|
||||
} else {
|
||||
double operand2 = operandStack.top();
|
||||
operandStack.pop();
|
||||
double operand1 = operandStack.top();
|
||||
operandStack.pop();
|
||||
double result = performOperation(operand1, operand2, token);
|
||||
operandStack.push(result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
那么我们在栈中变存储了我们想要的结果,最后返回top即可。
|
||||
|
||||
是不是很简单,欢迎与我一起探讨。
|
||||
116
site_extras/cpp-things-cpp-const-family.md
Normal file
116
site_extras/cpp-things-cpp-const-family.md
Normal file
@@ -0,0 +1,116 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-const-family/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ const 全家桶
|
||||
|
||||
大纲
|
||||
|
||||
- const
|
||||
- constexpr
|
||||
- C++20
|
||||
- consteval
|
||||
- constinit
|
||||
|
||||
**注:本文所有代码示例已放星球。**
|
||||
|
||||
## 1.const
|
||||
|
||||
`const` 是我们在学习 C++/C 时最早接触的关键字之一,通常作为 `cv-qualifier` 使用,表示对象不可变。它并不保证 **编译时评估**,具体何时评估由编译器决定。例如:
|
||||
|
||||
```cpp
|
||||
const int a = 1; // 编译时
|
||||
const auto x = getdata(); // 运行时
|
||||
```
|
||||
|
||||
const有时可以用于编译时常量表达式,但是有一些例外,例如:
|
||||
|
||||
```cpp
|
||||
const double count_1 = 3.3;
|
||||
std::array<double, static_cast<int>(count_1)> moreDoubles1 {1.1, 2.2, 3.3};
|
||||
```
|
||||
|
||||
此时便会报错:the value of 'count_1' is not usable in a constant expression
|
||||
|
||||
但是这样是正常的:
|
||||
|
||||
```cpp
|
||||
const int count = 3;
|
||||
std::array<double, count> doubles {1.1, 2.2, 3.3};
|
||||
```
|
||||
|
||||
本质在于编译时表达式求值,于是C++11引入了constexpr。
|
||||
|
||||
## 2.constexpr
|
||||
|
||||
constexpr 可以用来指定变量的值可以出现在常量表达式,此时只需要将前面例子的const变为constexpr,便可以正常运行。
|
||||
|
||||
```cpp
|
||||
constexpr double count_2 = 3.3;
|
||||
std::array<double, static_cast<int>(count_2)> moreDoubles2 {1.1, 2.2, 3.3};
|
||||
```
|
||||
|
||||
`constexpr` 并不一定只能在编译时执行。它的本质含义是 **可以** 在编译时计算,但如果在运行时使用 `constexpr` 变量或函数,它也可以在运行时执行。
|
||||
|
||||
例如:result1与result2完全不一样,result1是编译时计算,但是result2是运行时计算的,抛个疑问:**你知道为什么吗?**
|
||||
|
||||
所以并不是指定了constexpr的函数它就一定是编译时计算的。
|
||||
|
||||
```cpp
|
||||
constexpr int compileTimeSum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main() {
|
||||
constexpr int result1 = compileTimeSum(3, 5);
|
||||
int x = 10;
|
||||
int result2 = compileTimeSum(x, 20);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
那么谁能保证呢?于是C++20来了。
|
||||
|
||||
## 3.C++20
|
||||
|
||||
### 3.1 consteval
|
||||
|
||||
consteval解决了上面的问题,它只能用于函数,并强制所有调用在编译时进行。如果我们此时将上面的constexpr改为consteval,此时result2会发生什么呢?
|
||||
|
||||
那便是报错:call to consteval function '**compileTimeSum(x, 20)**' is not a constant expression
|
||||
|
||||
```cpp
|
||||
consteval int compileTimeSum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main() {
|
||||
constexpr int result1 = compileTimeSum(3, 5);
|
||||
int x = 10;
|
||||
int result2 = compileTimeSum(x, 20);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
如果使用了consteval使用在变量上,也会报错:**error:** a variable cannot be declared '**consteval**'。
|
||||
|
||||
> https://en.cppreference.com/w/cpp/language/consteval
|
||||
|
||||
### 3.2 constinit
|
||||
|
||||
constinit可以强制静态或线程局部变量进行常量初始化。
|
||||
|
||||
- 不能与 constexpr、consteval 一起使用
|
||||
- 一个非类型说明符,作用是assert
|
||||
- 保证变量是静态初始化
|
||||
- 只能用于 static 或者 thread_local
|
||||
|
||||
例如:下面会编译报错:error: 'constinit' can only be applied to a variable with static or thread storage duration
|
||||
|
||||
```cpp
|
||||
constinit int a = 100;
|
||||
int main() {
|
||||
++a;
|
||||
constinit auto b = 100; // error
|
||||
// b has thread storage duration
|
||||
constinit thread_local auto b = 100;
|
||||
}
|
||||
```
|
||||
78
site_extras/cpp-things-cpp-dereference-operator.md
Normal file
78
site_extras/cpp-things-cpp-dereference-operator.md
Normal file
@@ -0,0 +1,78 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-dereference-operator/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 解引用运算符 *
|
||||
|
||||
## 0.导语
|
||||
|
||||
通常我们在操作指针时,会使用到`*`,例如:
|
||||
|
||||
```cpp
|
||||
int a = 1;
|
||||
int *ptr = a;
|
||||
std::cout << *ptr << std::endl;
|
||||
```
|
||||
|
||||
除此之外,还有什么用途?
|
||||
|
||||
答案是肯定的,例如,在C++中还有下面三类:
|
||||
|
||||
- `::*`
|
||||
- `.*`
|
||||
- `->*`
|
||||
|
||||
那么你知道这三个分别表示什么吗?
|
||||
|
||||
## 1.::*
|
||||
|
||||
`::*`被称之为**Pointer to member declarator**,指向成员声明符的指针。
|
||||
|
||||
举个例子吧:
|
||||
|
||||
下面这个例子你如何区w_的地址呢?
|
||||
|
||||
如果你写成`double * d = &w_`; 它便是无效的,因为不知道`w_`在哪里哦,所以需要指向成员声明符的指针,这样便可以进行绑定,有了这个指针之后,便可以访问成员了,继续讲后面两个。
|
||||
|
||||
```cpp
|
||||
class Rectangle {
|
||||
public:
|
||||
double w_, h_;
|
||||
|
||||
Rectangle(double w, double h) : w_(w), h_(h) {}
|
||||
double area() { return w_ * h_; }
|
||||
};
|
||||
|
||||
int main() {
|
||||
Rectangle r{2.1, 3.2};
|
||||
double Rectangle::* w = &Rectangle::w_;
|
||||
r.*w = 2.2;
|
||||
std::cout << r.w_ << std::endl;
|
||||
};
|
||||
```
|
||||
|
||||
## 2..*
|
||||
|
||||
`.*`被称为pointer to member of object,这个比较好理解,就是访问**对象**成员的指针,指向成员的指针允许你引用类对象的非静态成员。不能使用指向成员的指针指向静态类成员,因为静态成员的地址与任何特定对象都没有关联。
|
||||
|
||||
所以看上面的例子中有了这一行代码,修改成员w的值为2.2。
|
||||
|
||||
```cpp
|
||||
r.*w = 2.2;
|
||||
```
|
||||
|
||||
## 3.->*
|
||||
|
||||
`->*`被称为pointer to member of pointer,这个就更好理解了,跟.*类似,不过操作的是**指针对象**成员的地址,
|
||||
|
||||
所以对应的例子变为:
|
||||
|
||||
```cpp
|
||||
Rectangle r{2.1, 3.2}, *pr;
|
||||
pr = &r;
|
||||
std::cout << pr->*w << std::endl;
|
||||
```
|
||||
|
||||
更加详细的请阅读cppreference.com。
|
||||
|
||||
> https://en.cppreference.com/w/cpp/language/pointer#Pointers_to_members
|
||||
|
||||
你学会了吗?本节完~
|
||||
83
site_extras/cpp-things-cpp-iv-initialization.md
Normal file
83
site_extras/cpp-things-cpp-iv-initialization.md
Normal file
@@ -0,0 +1,83 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-iv-initialization/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 初始化与赋值
|
||||
|
||||
## C++ iv
|
||||
|
||||
```cpp
|
||||
int* p = nullptr;
|
||||
std::shared_ptr<int> s(p); // 计数器1
|
||||
std::shared_ptr<int> s2(s); // 计数器2
|
||||
assert(s.use_count() == 2);
|
||||
```
|
||||
|
||||
这段代码会引发几个疑问:
|
||||
|
||||
- 为何nullptr原始指针构造出来的智能指针计数器不是0?
|
||||
- delete nullptr是否是安全的?
|
||||
|
||||
### 1.空的shared_ptr语义
|
||||
|
||||
我们直接看shared_ptr源码,所谓**空**指的是:
|
||||
|
||||
- 从默认构造一个shared_ptr
|
||||
- 从nullptr_t构造一个shared_ptr
|
||||
|
||||
这两种情况才是空,而对于从原始指针构造的shared_ptr,它占有那个指针的所有权,不管它是否为空。
|
||||
|
||||
分别对应下面三个构造。
|
||||
|
||||
```cpp
|
||||
private:
|
||||
element_type* __ptr_;
|
||||
__shared_weak_count* __cntrl_;
|
||||
|
||||
public:
|
||||
_LIBCPP_HIDE_FROM_ABI
|
||||
_LIBCPP_CONSTEXPR shared_ptr() _NOEXCEPT
|
||||
: __ptr_(nullptr),
|
||||
__cntrl_(nullptr)
|
||||
{ }
|
||||
|
||||
_LIBCPP_HIDE_FROM_ABI
|
||||
_LIBCPP_CONSTEXPR shared_ptr(nullptr_t) _NOEXCEPT
|
||||
: __ptr_(nullptr),
|
||||
__cntrl_(nullptr)
|
||||
{ }
|
||||
shared_ptr(_Yp* __p, _Dp __d)
|
||||
: __ptr_(__p)
|
||||
{}
|
||||
```
|
||||
|
||||
在上面原始指针式nullptr情况下,删除delete nullptr会发生什么?删除两次又回发生什么?
|
||||
|
||||
### 2.delete nullptr
|
||||
|
||||
假设有下面的代码,运行之后会crush?会正常运行?
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
int *p = nullptr;
|
||||
delete p;
|
||||
std::cout << "delete once" << std::endl;
|
||||
delete p;
|
||||
std::cout << "delete twice" << std::endl;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
答案是:正常输出。
|
||||
|
||||
具体原因参考cppreference:
|
||||
|
||||
If *expression* evaluates to a null pointer value, no destructors are called, and the deallocation function may or may not be called (it's unspecified), but the default deallocation functions are guaranteed to do nothing when passed a null pointer.
|
||||
|
||||
> https://en.cppreference.com/w/cpp/language/delete
|
||||
|
||||
如果表达式的计算结果为空指针值,则不会调用析构函数,也可能调用或不调用释放函数(未指定),但默认的释放函数保证在传递空指针时不做任何事情。
|
||||
|
||||
|
||||
!!! note "阅读提示"
|
||||
本文讨论 C++ 中**初始化**(initialization)与**赋值**(assignment)的区别,可参见 [类初始化列表](../cpp-idioms/class-initializer-list.md)。
|
||||
147
site_extras/cpp-things-cpp-multiple-return-values.md
Normal file
147
site_extras/cpp-things-cpp-multiple-return-values.md
Normal file
@@ -0,0 +1,147 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-multiple-return-values/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 多返回值写法
|
||||
|
||||
[TOC]
|
||||
|
||||
今天再提出一个比较经典的面试题:函数如何返回多个结果?你能想到几种办法?
|
||||
|
||||
其实这道题目考察的知识点非常的多,涉及到:
|
||||
|
||||
- 指针
|
||||
- 引用
|
||||
- lambda
|
||||
- functional
|
||||
- tie
|
||||
- tuple
|
||||
- struct bingding
|
||||
- template deduce
|
||||
- 等等
|
||||
|
||||
本篇文章将会给大家用不同的方法来解答这道题目,首先我们转化一下这个题目,使用`a / b`来模拟(下面不考虑被除数为0的场景),返回商与余数。简单来说转化为一个函数返回商与余数有多少种办法?
|
||||
|
||||
下面进入正文,注:本节的所有代码已首发于星球,感兴趣戳下方二维码即可。
|
||||
|
||||
## 1. 指针与引用
|
||||
|
||||
对接口进行更改,添加两个变量,使用指针与引用。
|
||||
|
||||
```cpp
|
||||
void divideWithReferences(int dividend, int divisor, int& quotient, int& remainder) {
|
||||
quotient = dividend / divisor;
|
||||
remainder = dividend % divisor;
|
||||
}
|
||||
|
||||
void divideWithPointers(int dividend, int divisor, int* quotient, int* remainder) {
|
||||
if (quotient) *quotient = dividend / divisor;
|
||||
if (remainder) *remainder = dividend % divisor;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
使用这种方式的缺点也明显可见,当返回值不止两个,接口就非常的长。此外,如果面试官要求你不允许更改函数接口,那么这个办法用不了了。
|
||||
|
||||
## 2. Tuple + Tie
|
||||
|
||||
Tuple和tie的组合为函数返回多个值提供了一种简洁的方式。通过使用`std::tie`,我们可以将tuple中的元素解包到不同的变量中,提高代码的清晰度。
|
||||
|
||||
这种方法算是标准答案之一,比较简单清晰,如果返回值是两个pair也可以。
|
||||
|
||||
```cpp
|
||||
std::tuple<int, int> divide(int dividend, int divisor) {
|
||||
return std::make_tuple(dividend / divisor, dividend % divisor);
|
||||
}
|
||||
|
||||
|
||||
std::tie(quotient, remainder) = divide(14, 3);
|
||||
std::cout << quotient << ", " << remainder << std::endl;
|
||||
```
|
||||
|
||||
## 3. Struct Binding
|
||||
|
||||
对上面进行改造,C++17引入的结构化绑定进一步简化了多值返回的代码。使用auto和结构化绑定,使得代码更加直观易懂。
|
||||
|
||||
如果面试官要你进一步的对上面的方法进行改造,那么可以变为下面这个代码示例,使用结构化绑定使代码更加优雅。
|
||||
|
||||
```cpp
|
||||
auto divide(int dividend, int divisor) {
|
||||
struct result {
|
||||
int quotient;
|
||||
int remainder;
|
||||
};
|
||||
return result{dividend / divisor, dividend % divisor};
|
||||
}
|
||||
auto [quotient, remainder] = divide(14, 3);
|
||||
```
|
||||
|
||||
## 4. 函数 Callback
|
||||
|
||||
在日常项目中,特别是一些开源项目,callback是一种常用的手段,通过传递处理返回值的callback,让用户自定义处理,这样便实现了返回多个值,实现更加灵活的代码结构。这对于异步编程和事件处理等场景非常有用。
|
||||
|
||||
```cpp
|
||||
void divide(int dividend, int divisor, std::function<void(int, int)> callback) {
|
||||
callback(dividend / divisor, dividend % divisor);
|
||||
}
|
||||
```
|
||||
|
||||
## 5. 自定义 Out
|
||||
|
||||
自定义out是一种通过结构体包装的方式,将输出参数作为结构体的成员。这种方式提高了代码的可读性,尤其适用于需要返回多个值的函数。
|
||||
|
||||
```cpp
|
||||
template <class T>
|
||||
struct out {
|
||||
std::function<void(T)> target;
|
||||
|
||||
out(T* t)
|
||||
: target([t](T&& in) {
|
||||
if (t) *t = std::move(in);
|
||||
}) {}
|
||||
|
||||
template <class... Args>
|
||||
void emplace(Args&&... args) {
|
||||
target(T(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
template <class X>
|
||||
void operator=(X&& x) {
|
||||
emplace(std::forward<X>(x));
|
||||
}
|
||||
|
||||
template <class... Args>
|
||||
void operator()(Args&&... args) {
|
||||
emplace(std::forward<Args>(args)...);
|
||||
}
|
||||
};
|
||||
|
||||
void divide(int dividend, int divisor, out<int>& quotient_out, out<int>& remainder_out) {
|
||||
quotient_out.emplace(dividend / divisor);
|
||||
remainder_out.emplace(dividend % divisor);
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 模版推导
|
||||
|
||||
C++的模版推导为开发者提供了更为灵活和简洁的代码编写方式。通过模版推导,我们可以处理不同类型的数据而无需显式指定类型。
|
||||
|
||||
```cpp
|
||||
template <typename T1, typename T2>
|
||||
struct many {
|
||||
T1 quotient;
|
||||
T2 remainder;
|
||||
};
|
||||
|
||||
template <class T1, class T2>
|
||||
many(T1, T2) -> many<T1, T2>;
|
||||
|
||||
many<int, int> divide(int dividend, int divisor) {
|
||||
return many{
|
||||
dividend / divisor,
|
||||
dividend % divisor,
|
||||
};
|
||||
}
|
||||
|
||||
auto [quotient, remainder] = divide(14, 3);
|
||||
```
|
||||
|
||||
总体而言,C++提供了多种方式来实现多值返回,每种方式都有其适用的场景。选择合适的方式取决于具体的需求,开发者可以根据代码结构和可读性来灵活使用这些特性。
|
||||
75
site_extras/cpp-things-cpp-mutable-keyword.md
Normal file
75
site_extras/cpp-things-cpp-mutable-keyword.md
Normal file
@@ -0,0 +1,75 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-mutable-keyword/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ mutable 关键字
|
||||
|
||||
### 深入探讨 C++ 中的 `mutable` 关键字
|
||||
|
||||
在 C++ 中,`mutable` 关键字经常被认为是“穿透”常量(`const`)限制的工具。在某些情况下,虽然我们希望对一个对象施加常量保护,但还是需要对该对象的某些数据成员进行修改。本文将详细探讨 `mutable` 的使用场景和背后的设计哲学,并讨论其如何在 C++ 中解决特定的编程需求。
|
||||
|
||||
#### 1. `mutable` 关键字的基本用途
|
||||
|
||||
我们知道,当一个成员函数被 `const` 修饰时,该成员函数保证不会修改对象的状态。然而,在实际编程中,有时我们希望修改一个数据成员,但仍然希望将成员函数标记为 `const`。这就是 `mutable` 关键字的作用:
|
||||
|
||||
```cpp
|
||||
class Foo
|
||||
{
|
||||
private:
|
||||
mutable bool done_;
|
||||
public:
|
||||
void doSomething() const {
|
||||
// 在 const 成员函数中修改 mutable 成员
|
||||
done_ = true;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
在上面的例子中,`doSomething()` 被声明为 `const`,表明它不会改变对象的状态。然而,`done_` 被标记为 `mutable`,这意味着即使在 `const` 方法中,我们仍然可以修改 `done_`。这种设计使得我们可以在保持函数接口语义不变的情况下,管理某些需要修改的数据。
|
||||
|
||||
#### 2. 逻辑常量性 vs. 位常量性
|
||||
|
||||
C++ 中的常量性可以分为两类:**逻辑常量性** 和 **位常量性**。逻辑常量性指的是对象的状态在外部看来没有发生变化,而位常量性指的是对象在内存中的位数据保持不变。`mutable` 关键字允许我们定义逻辑常量性,即即使对象的某些内部数据变化了,但在逻辑上对象的状态并未发生可见变化。
|
||||
|
||||
比如在一个线程安全的类中,我们可能会使用 `boost::mutex` 来保护数据访问。为了在 `const` 方法中获取锁,我们可以将 `mutex` 声明为 `mutable`:
|
||||
|
||||
```cpp
|
||||
class ThreadSafeClass {
|
||||
private:
|
||||
mutable std::mutex mtx_;
|
||||
int data_;
|
||||
public:
|
||||
int getData() const {
|
||||
std::lock_guard<std::mutex> lock(mtx_);
|
||||
return data_;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
在上述例子中,虽然 `getData` 方法被声明为 `const`,但我们需要锁来保护数据访问的线程安全性。因此,我们将 `mtx_` 声明为 `mutable`,以允许在 `const` 方法中对其进行修改。这种情况下,我们说类的逻辑状态没有改变,只是为确保线程安全而进行的修改。
|
||||
|
||||
#### 3. 在 Lambda 表达式中的 `mutable`
|
||||
|
||||
从 C++11 开始,`mutable` 也可以用于 lambda 表达式,以允许修改按值捕获的变量。默认情况下,lambda 中按值捕获的变量是不可变的。如果需要在 lambda 中修改捕获的变量,可以使用 `mutable`:
|
||||
|
||||
```cpp
|
||||
int x = 0;
|
||||
auto f1 = [=]() mutable { x = 42; }; // OK: 可以修改捕获的 x
|
||||
auto f2 = [=]() { x = 42; }; // Error: 按值捕获的变量不能被修改
|
||||
```
|
||||
|
||||
这种情况下,`mutable` 允许我们在函数体内修改捕获的变量,而不会影响到外部变量的值。
|
||||
|
||||
#### 4. 避免使用 `const_cast`
|
||||
|
||||
没有 `mutable` 关键字的情况下,我们可能需要使用 `const_cast` 来处理这些特殊情况。`const_cast` 可以去掉对象的常量性,但它也有缺点:`const_cast` 可以完全移除常量性保护,让我们对对象进行任意的修改和方法调用,这会导致代码的可读性和安全性下降。
|
||||
|
||||
相比之下,`mutable` 关键字提供了一种更细粒度的控制方式。通过 `mutable`,我们可以在特定的数据成员上设置“例外”,允许在 `const` 方法中修改,而不必将整个对象的常量性去掉。因此,`mutable` 能够更安全地处理这些特例。
|
||||
|
||||
#### 5. 使用 `mutable` 的设计哲学
|
||||
|
||||
`mutable` 关键字的设计哲学在于保持接口的**逻辑常量性**。在大多数情况下,我们希望编写 const-correct 的代码,这意味着对象的状态在没有显式修改的情况下不会变化。`mutable` 允许我们在某些内部实现上做出让步,比如缓存、引用计数、调试信息等,而不会打破这种接口设计的一致性。
|
||||
|
||||
设计一个接口时,我们应该明确何时以及为什么需要修改一个对象的状态。`mutable` 关键字能让代码在逻辑层面保持不变,同时又提供了修改特定数据成员的能力。这需要设计者深思熟虑,确保 `mutable` 的使用不会破坏对象的常量性概念,只有在确实需要的情况下使用。
|
||||
|
||||
### 6.参考资料
|
||||
|
||||
> https://stackoverflow.com/questions/105014/does-the-mutable-keyword-have-any-purpose-other-than-allowing-a-data-member-to
|
||||
96
site_extras/cpp-things-cpp-restrict-optimization.md
Normal file
96
site_extras/cpp-things-cpp-restrict-optimization.md
Normal file
@@ -0,0 +1,96 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-restrict-optimization/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ restrict 与编译优化
|
||||
|
||||
## restrict性能优化
|
||||
|
||||
```cpp
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#define LEN 1<<20
|
||||
using AggregateDataPtr = char *;
|
||||
|
||||
struct AvgState {
|
||||
uint64_t numerator{0};
|
||||
uint64_t denominator{0};
|
||||
|
||||
double divide() { return numerator / denominator; }
|
||||
};
|
||||
|
||||
class Column {
|
||||
public:
|
||||
std::vector<uint64_t> & data() {return data_; }
|
||||
|
||||
private:
|
||||
std::vector<uint64_t> data_;
|
||||
};
|
||||
|
||||
template <class Derived>
|
||||
class IAggregate {
|
||||
public:
|
||||
void addBatch(size_t batch_size, AggregateDataPtr state, Column *args) __attribute__((noinline)) {
|
||||
for (size_t i = 0; i < batch_size; ++i) {
|
||||
static_cast<const Derived *>(this)->add(state, args, i);
|
||||
}
|
||||
}
|
||||
|
||||
void addBatchWithoutOpt(size_t batch_size, AggregateDataPtr state, Column *args) __attribute__((noinline)) {
|
||||
for (size_t i = 0; i < batch_size; ++i) {
|
||||
static_cast<const Derived *>(this)->addWithoutOpt(state, args, i);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class AvgAggregator final : public IAggregate<AvgAggregator> {
|
||||
public:
|
||||
static AvgState& data(AggregateDataPtr __restrict place) { return *reinterpret_cast<AvgState *>(place); }
|
||||
static AvgState& data_without_opt(AggregateDataPtr place) { return *reinterpret_cast<AvgState *>(place); }
|
||||
|
||||
void add(AggregateDataPtr __restrict state, Column * args, uint64_t row_num) const {
|
||||
data(state).numerator += args[0].data()[row_num];
|
||||
++(data(state).denominator);
|
||||
}
|
||||
|
||||
void addWithoutOpt(AggregateDataPtr state, Column * args, uint64_t row_num) const {
|
||||
data_without_opt(state).numerator += args[0].data()[row_num];
|
||||
++(data_without_opt(state).denominator);
|
||||
}
|
||||
};
|
||||
|
||||
static void BM_loop_with_optimize(benchmark::State& state) {
|
||||
AvgAggregator avgAggregator;
|
||||
Column column;
|
||||
for (size_t i = 0 ; i < LEN; i++) {
|
||||
column.data().push_back(i);
|
||||
}
|
||||
Column arg0[] = {column};
|
||||
// Code inside this loop is measured repeatedly
|
||||
for(auto _ : state) {
|
||||
auto avgState = std::make_unique<AvgState>();
|
||||
avgAggregator.addBatch(LEN, reinterpret_cast<AggregateDataPtr>(avgState.get()), arg0);
|
||||
}
|
||||
}
|
||||
|
||||
static void BM_loop_without_optimize(benchmark::State& state) {
|
||||
AvgAggregator avgAggregator;
|
||||
Column column;
|
||||
for (size_t i = 0 ; i < LEN; i++) {
|
||||
column.data().push_back(i);
|
||||
}
|
||||
Column arg0[] = {column};
|
||||
// Code inside this loop is measured repeatedly
|
||||
for(auto _ : state) {
|
||||
auto avgState = std::make_unique<AvgState>();
|
||||
avgAggregator.addBatchWithoutOpt(LEN, reinterpret_cast<AggregateDataPtr>(avgState.get()), arg0);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(BM_loop_without_optimize);
|
||||
BENCHMARK(BM_loop_with_optimize);
|
||||
```
|
||||
|
||||
> https://quick-bench.com/q/ccjuWr_JcLozAfy3Gxf3uVu76Yk
|
||||
|
||||
https://github.com/ClickHouse/ClickHouse/pull/19946
|
||||
99
site_extras/cpp-things-cpp-string-abi-compatibility.md
Normal file
99
site_extras/cpp-things-cpp-string-abi-compatibility.md
Normal file
@@ -0,0 +1,99 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-string-abi-compatibility/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ string ABI 兼容性
|
||||
|
||||
### 项目实战问题:避坑 C++ String ABI 兼容性问题
|
||||
|
||||
[TOC]
|
||||
|
||||
为什么很多人不喜欢C++ string,反而要自己造轮子呢?其中一个问题就是C++ string abi问题,你遇到过吗?
|
||||
|
||||
之前使用conan与跨平台库的时候发生了C++ string abi兼容问题,本节将会引入ABI的背景与编译器相关的内容,讲讲如何避免这个坑,如果你遇到过,欢迎留言~
|
||||
|
||||
#### 1. ABI 变更的背景
|
||||
|
||||
**GCC 5.1**之后加强了对 C++11 的支持,并引入了一些新特性。在这一版本中,libstdc++ 引入了新的库 ABI,更新了 `std::string` 和 `std::list` 的实现。这些变化符合 C++11 标准,后者禁止使用 Copy-On-Write 字符串,并要求链表能够跟踪其大小。
|
||||
|
||||
实际项目中在使用 Conan 时,开发者可以通过调整 `compiler.libcxx` 来选择使用的 ABI:
|
||||
|
||||
- **libstdc++**:使用旧 ABI。
|
||||
- **libstdc++11**:使用新 ABI。
|
||||
|
||||
选择适当的 ABI 可以确保与其他依赖库的兼容性,特别是在使用不同版本的编译器或库时。
|
||||
|
||||
#### 2. 编译器的默认设置
|
||||
|
||||
在使用 GCC 进行编译时,如果没有显式地指定 `--with-default-libstdcxx-abi=gcc4-compatible`,则 GCC 默认使用新的 C++11 ABI。这意味着:
|
||||
|
||||
- 如果你的代码或依赖库是在旧 ABI 下编译的,那么当你尝试链接时,可能会遇到未定义的符号错误。
|
||||
|
||||
例如,编译以下代码时:
|
||||
|
||||
```cpp
|
||||
// lib.cc
|
||||
#include <string>
|
||||
void foo(const std::string& s) {}
|
||||
```
|
||||
|
||||
使用命令:
|
||||
|
||||
```bash
|
||||
g++-14 -D_GLIBCXX_USE_CXX11_ABI=0 -c lib.cc
|
||||
```
|
||||
|
||||
将生成符号 `__Z3fooRKSs`,这是旧 ABI 的格式。
|
||||
|
||||
然而,当你编译并链接另一个使用新 ABI 的文件时,可能会出现如下错误:
|
||||
|
||||
```bash
|
||||
g++-14 main.cc lib.o
|
||||
```
|
||||
|
||||
```
|
||||
Undefined symbols for architecture x86_64:
|
||||
"foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
|
||||
_main in ccbWGoYh.o
|
||||
ld: symbol(s) not found for architecture x86_64
|
||||
collect2: error: ld returned 1 exit status
|
||||
```
|
||||
|
||||
#### 3. 解决方案
|
||||
|
||||
为了确保编译通过,有以下两种解决方案:
|
||||
|
||||
**方法 1: 手动指定 ABI**
|
||||
|
||||
在编译所有源文件时,确保手动添加 `-D_GLIBCXX_USE_CXX11_ABI=0` 来兼容旧的库,例如:
|
||||
|
||||
```bash
|
||||
g++-14 -D_GLIBCXX_USE_CXX11_ABI=0 main.cc lib.o
|
||||
```
|
||||
|
||||
**方法 2: 使用新的 ABI 编译所有文件**
|
||||
|
||||
如果你愿意使用新的 C++11 ABI,可以在编译库文件时使用 `-D_GLIBCXX_USE_CXX11_ABI=1`,这样两者符号就会匹配:
|
||||
|
||||
```bash
|
||||
g++-14 -D_GLIBCXX_USE_CXX11_ABI=1 -c lib.cc
|
||||
g++-14 main.cc lib.o
|
||||
```
|
||||
|
||||
此时,链接时符号将会匹配,不再出现未定义符号的错误。
|
||||
|
||||
#### 4. 符号比较
|
||||
|
||||
通过 `nm` 命令查看不同 ABI 下的符号,可以直观地看到二者的差异:
|
||||
|
||||
```bash
|
||||
g++-14 -D_GLIBCXX_USE_CXX11_ABI=0 -c lib.cc
|
||||
nm lib.o | grep foo
|
||||
# 输出: 0000000000000000 T __Z3fooRKSs
|
||||
|
||||
g++-14 -D_GLIBCXX_USE_CXX11_ABI=1 -c lib.cc
|
||||
nm lib.o | grep foo
|
||||
# 输出: 0000000000000000 T __Z3fooRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
|
||||
```
|
||||
|
||||
#### 5. 小结
|
||||
|
||||
ABI是C++升级以及编译过程中遇到的一个非常大的坑,希望可以通过这篇文章讲明白这些内容。
|
||||
57
site_extras/cpp-things-cpp-template-disambiguator.md
Normal file
57
site_extras/cpp-things-cpp-template-disambiguator.md
Normal file
@@ -0,0 +1,57 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-template-disambiguator/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 模板消歧
|
||||
|
||||
## 1.背景
|
||||
|
||||
最近看到一段代码:
|
||||
|
||||
```cpp
|
||||
auto chunk_left = first_sort_key.template GetChunk<ArrayType>(left);
|
||||
```
|
||||
|
||||
请问,这里的`.template`代表什么意义?
|
||||
|
||||
本节将从实际例子出发,探讨这个意义。
|
||||
|
||||
## 2.template disambiguator
|
||||
|
||||
在C++中,当使用模板的依赖名称(dependent names)时,有时需要使用模板消除符(template disambiguator)来帮助编译器区分这些名称。所谓"dependent names"是指依赖于模板参数的类型或值,编译器不能在实例化模板之前确定它们的具体含义。这可能会导致编译器在解析这些名称时产生二义性。
|
||||
|
||||
模板消除符(template disambiguator)使用关键字"template"来明确告诉编译器一个特定的名称是一个模板。这样编译器就可以正确地解析该名称,而不会产生二义性。
|
||||
|
||||
关键字template只能在操作符::(作用域解析)、->(通过指针访问成员)和.(成员访问),以下都是有效的示例
|
||||
|
||||
- T::template foo<X>();
|
||||
- s.template foo<X>();
|
||||
- this->template foo<X>();
|
||||
- typename T::template iterator<int>::value_type v;
|
||||
|
||||
官方资料:
|
||||
|
||||
> https://en.cppreference.com/w/cpp/language/dependent_name
|
||||
|
||||
假设有下面这个代码,我们如果不加.template会得到什么?
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
auto foo_is_not_a_template() {
|
||||
// ((T::foo) < 34) > (::val())
|
||||
return T::foo<34>::val();
|
||||
}
|
||||
```
|
||||
|
||||
上述会被解析为:((T::foo) < 34) > (::val())
|
||||
|
||||
对应的.template例子为:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
auto foo_is_a_template() {
|
||||
return T::template foo<34>::val();
|
||||
}
|
||||
```
|
||||
|
||||
这样便调用会正确解析为模版,foo<34>。
|
||||
|
||||
本节完整代码将会在星球公布,感兴趣加入即可,谢谢!
|
||||
58
site_extras/cpp-things-cpp-vs-rust-destructor.md
Normal file
58
site_extras/cpp-things-cpp-vs-rust-destructor.md
Normal file
@@ -0,0 +1,58 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/cpp-vs-rust-destructor/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 与 Rust 析构对比
|
||||
|
||||
在Rust中mem::forget用于防止对象的析构,跳过清理工作,从而让资源的释放交给其他机制管理。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
let file = File::open("foo.txt").unwrap();
|
||||
mem::forget(file);
|
||||
```
|
||||
|
||||
那么在C++中如何防止析构?即跳过析构函数呢?
|
||||
|
||||
**本节将给出三种办法,完整代码示例也放于星球。**
|
||||
|
||||
## 1. `placement new`
|
||||
|
||||
`placement new`可以让我们手动管理对象的构造和析构。如果不手动调用对象的析构函数,我们就可以跳过对象的析构,从而实现类似`mem::forget`的效果。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
alignas(Foo) std::byte storage[sizeof(Foo)]; // 分配对齐的原始内存块
|
||||
Foo* pfoo = new (storage) Foo(); // 在这块内存上构造Foo对象
|
||||
```
|
||||
|
||||
在上面的代码中,`placement new`创建了对象`pfoo`,但我们不调用析构函数,这样可以跳过对象的清理逻辑。
|
||||
|
||||
## 2. 使用智能指针的自定义删除器
|
||||
|
||||
另一种实现类似功能的方法是通过自定义智能指针的删除器,防止对象被销毁。我们可以定义一个不执行任何操作的删除器,从而避免析构函数的调用。
|
||||
|
||||
```cpp
|
||||
std::unique_ptr<Foo, NoOpDeleter> pfoo(new Foo(), NoOpDeleter{});
|
||||
```
|
||||
|
||||
使用自定义的删除器`NoOpDeleter`,我们可以防止`std::unique_ptr`在离开作用域时调用析构函数,从而实现类似`mem::forget`的效果。
|
||||
|
||||
## 3.union
|
||||
|
||||
union的方案很神奇,大家知道原理吗?欢迎留言区一起讨论~
|
||||
|
||||
```cpp
|
||||
template <class T>
|
||||
union Wrapper {
|
||||
T value;
|
||||
~Wrapper() {}
|
||||
};
|
||||
|
||||
struct Foo {
|
||||
~Foo() { std::cout << "dtor foo\n"; }
|
||||
};
|
||||
|
||||
Wrapper<Foo> f;
|
||||
// f.value.~Foo); 必须手动调用
|
||||
```
|
||||
82
site_extras/cpp-things-member-initializer-list-notes.md
Normal file
82
site_extras/cpp-things-member-initializer-list-notes.md
Normal file
@@ -0,0 +1,82 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/member-initializer-list-notes/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 成员初始化列表注意点
|
||||
|
||||
在C++中,类的正确初始化是确保程序正常运行的关键步骤之一。尤其是在使用初始化列表时,我们需要注意一些潜在的陷阱,以避免在代码执行过程中产生意外的结果。
|
||||
|
||||
初始化列表通常被认为是设置新类实例状态的首选方法,因为它提供了一种简洁、高效的方式来初始化类成员。然而,有时候在初始化列表中引用其他成员变量可能导致一些令人困惑的问题。
|
||||
|
||||
## 问题示例
|
||||
|
||||
考虑以下的`Foo`类:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
class Foo
|
||||
{
|
||||
public:
|
||||
Foo(int size) : size_(size),
|
||||
capacity_(size_ + 2),
|
||||
length_(capacity_)
|
||||
{}
|
||||
|
||||
void print() {
|
||||
std::cout << "Size: " << size_ << " Capacity: " << capacity_ << " Length: " << length_ << std::endl;
|
||||
}
|
||||
|
||||
private:
|
||||
int length_;
|
||||
int capacity_;
|
||||
int size_;
|
||||
};
|
||||
|
||||
int main() {
|
||||
Foo foo(50);
|
||||
foo.print();
|
||||
}
|
||||
```
|
||||
|
||||
在这个例子中,我们试图通过初始化列表中引用其他成员变量的方式来初始化`length_`、`capacity_`和`size_`。然而,由于类成员的初始化顺序是按照它们在类中声明的顺序进行的,可能导致`length_`与`capacity_`并没有按照我们期望的方式初始化。
|
||||
|
||||
## 如何解决?
|
||||
|
||||
为了避免这种问题,应该遵循以下几点:
|
||||
|
||||
**1.避免在初始化列表中引用其他成员变量**
|
||||
|
||||
**2.顺序一致性:成员变量的初始化顺序是按照它们在类中声明的顺序**
|
||||
|
||||
修正示例:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
class Foo
|
||||
{
|
||||
public:
|
||||
Foo(int size) : size_(size),
|
||||
capacity_(size_ + 2),
|
||||
length_(calculateLength(size_))
|
||||
{}
|
||||
|
||||
void print() {
|
||||
std::cout << "Size: " << size_ << " Capacity: " << capacity_ << " Length: " << length_ << std::endl;
|
||||
}
|
||||
|
||||
private:
|
||||
int calculateLength(int size) {
|
||||
return size + 2;
|
||||
}
|
||||
|
||||
private:
|
||||
int size_;
|
||||
int capacity_;
|
||||
int length_;
|
||||
};
|
||||
|
||||
int main() {
|
||||
Foo foo(50);
|
||||
foo.print();
|
||||
}
|
||||
```
|
||||
73
site_extras/cpp-things-smart-pointer-as-parameter.md
Normal file
73
site_extras/cpp-things-smart-pointer-as-parameter.md
Normal file
@@ -0,0 +1,73 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/smart-pointer-as-parameter/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 智能指针作函数参数
|
||||
|
||||
## C++那些事之智能指针何时作为函数参数
|
||||
|
||||
通常我们可以看到有些函数用了智能指针作为参数,有些函数又使用了裸指针,究竟用哪一个呢?使用原则是什么?
|
||||
|
||||
本节使用abseil的tips进行讲解。
|
||||
|
||||
如下所示,这段代码有什么问题呢?
|
||||
|
||||
```cpp
|
||||
bool CanYouPetTheDog(const std::shared_ptr<Dog>& dog,
|
||||
absl::Duration min_delay) {
|
||||
return dog->GetLastPetTime() + min_delay < absl::Now();
|
||||
}
|
||||
```
|
||||
|
||||
CanYouPetTheDog函数并不会影响其 dog 参数的所有权,但它的签名要求将其存储在 std::shared_ptr 中。这样做会在特定所有权模型上创建一个不必要的依赖,尽管函数本身并不需要这种依赖。这种依赖会阻止调用者使用其他模型,比如 std::unique_ptr 或在堆栈上构造对象。
|
||||
|
||||
## 使用指针/引用
|
||||
|
||||
当所有权没有受到影响时使用**引用或指针**。 通过使用引用/指针,我们可以消除对特定所有权模型的依赖,并允许我们的函数与任何类型为 Dog 的对象一起工作。
|
||||
|
||||
```cpp
|
||||
bool CanYouPetTheDog(const Dog& dog, absl::Duration min_delay) {
|
||||
return dog.GetLastPetTime() + min_delay < absl::Now();
|
||||
}
|
||||
```
|
||||
|
||||
有了上述定义,无论调用者的所有权模型如何,都可以调用该函数:
|
||||
|
||||
```cpp
|
||||
Dog stack_dog;
|
||||
if (CanYouPetTheDog(stack_dog, delay)) { ... }
|
||||
|
||||
auto heap_dog = std::make_unique<Dog>();
|
||||
if (CanYouPetTheDog(*heap_dog, delay)) { ... }
|
||||
|
||||
CustomPetPtr<Dog> custom_dog = CreateDog();
|
||||
if (CanYouPetTheDog(*custom_dog, delay)) { ... }
|
||||
```
|
||||
|
||||
函数修改了传递的值,则传递可变引用或原始指针,并使用与上述相同的用法。
|
||||
|
||||
## 使用智能指针
|
||||
|
||||
在函数修改所有权时使用智能指针,以下代码为不同的智能指针参数提供了几个重载。第一个重载假定接管传递对象的所有权,第二个重载为传递对象添加了一个共享引用。这两种操作取决于调用方如何处理 Dog 的所有权。无法接管位于栈的 Dog,因为无法从栈中取走所有权。
|
||||
|
||||
```cpp
|
||||
class Human {
|
||||
public:
|
||||
...
|
||||
void Adopt(std::unique_ptr<Dog> dog) {
|
||||
pets_.push_back(std::move(dog));
|
||||
}
|
||||
void Adopt(std::shared_ptr<Cat> cat) {
|
||||
pets_.push_back(std::move(cat));
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Pet>> pets_;
|
||||
...
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
如果所有权没有被转移或修改,则应该避免将智能指针作为函数参数。
|
||||
|
||||
> https://abseil.io/tips/188
|
||||
78
site_extras/cpp-things-std-function-cpp.md
Normal file
78
site_extras/cpp-things-std-function-cpp.md
Normal file
@@ -0,0 +1,78 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/std-function-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ std::function 详解
|
||||
|
||||
最近在写C++代码时用到了`is_function`,然后顺便看了一下源码实现,发现了一些问题,以前咱们学习的是三个点`...`,那六个点`......`你知道是啥吗?
|
||||
|
||||
同样,如果有一段这样的代码:
|
||||
|
||||
```
|
||||
template<typename... Args>
|
||||
struct foo(Args......);
|
||||
```
|
||||
|
||||
你知道是啥意思?
|
||||
|
||||
下面我们一起来深入细节!
|
||||
|
||||
## 1.六个点
|
||||
|
||||
六个点我们通常叫做two ellipsis operators,我们可以将六个点进行拆分,于是得到下面三种情况
|
||||
|
||||
```
|
||||
template <typename... Args> void foo1(Args......)
|
||||
template <typename... Args> void foo2(Args... ...)
|
||||
template <typename... Args> void foo3(Args..., ...)
|
||||
```
|
||||
|
||||
这下就好看了,我们来看std::is_function的代码。
|
||||
|
||||
## 2.is_function实现细节
|
||||
|
||||
`std::is_function`的实现涉及到主模板和两个偏特化:
|
||||
|
||||
```cpp
|
||||
// 主模板,假设提供的类型不是函数类型
|
||||
template<typename T>
|
||||
struct is_function : std::false_type {};
|
||||
|
||||
// 偏特化,用于正常的函数类型
|
||||
template<typename Ret, typename... Args>
|
||||
struct is_function<Ret(Args...)> : std::true_type {};
|
||||
|
||||
// 偏特化,用于变参函数类型
|
||||
template<typename Ret, typename... Args>
|
||||
struct is_function<Ret(Args......)> : std::true_type {};
|
||||
```
|
||||
|
||||
- 主模板假设提供的类型不是函数类型,并将`std::false_type`作为结果。
|
||||
- 第一个偏特化用于正常的函数类型,其中`Ret`表示返回类型,`Args...`表示参数类型。如果提供的类型匹配这种函数签名,则`std::true_type`作为结果。
|
||||
- 第二个偏特化用于变参函数类型,其中的省略号表示函数具有可变数量的参数。同样,如果提供的类型匹配这种函数签名,则`std::true_type`作为结果。
|
||||
|
||||
## 3.使用示例
|
||||
|
||||
最后给出一个`std::is_function`的使用示例:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <type_traits>
|
||||
|
||||
int func(int x, int y) { return x + y; }
|
||||
int vararg_func(int x, ...) { return x; }
|
||||
|
||||
int main() {
|
||||
std::cout << std::boolalpha;
|
||||
std::cout << "Is func a function? " << std::is_function<decltype(func)>::value << std::endl;
|
||||
std::cout << "Is vararg_func a function? " << std::is_function<decltype(vararg_func)>::value << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
这将输出:
|
||||
|
||||
```
|
||||
Is func a function? true
|
||||
Is vararg_func a function? true
|
||||
```
|
||||
|
||||
你学会了吗,本节完~
|
||||
146
site_extras/cpp-things-std-ref-wrapper.md
Normal file
146
site_extras/cpp-things-std-ref-wrapper.md
Normal file
@@ -0,0 +1,146 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/std-ref-wrapper/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ ref 与 reference_wrapper
|
||||
|
||||
## 深入理解 C++ 中的 std::cref、std::ref 和 std::reference_wrapper
|
||||
|
||||
在 C++ 编程中,有时候我们需要在不进行拷贝的情况下传递引用,或者在需要引用的地方使用常量对象。为了解决这些问题,C++ 标准库提供了三个有用的工具:`std::cref`、`std::ref` 和 `std::reference_wrapper`。这篇文章将深入探讨这些工具的用途、区别以及实际应用。
|
||||
|
||||
此外,我们知道Rust语言中,经常实现了Unwrap方法,在C++中如何实现?
|
||||
|
||||
这就参考Apache arrow的代码了,有这么一段:
|
||||
|
||||
```cpp
|
||||
std::optional<std::reference_wrapper<const TransportStatusDetail>>
|
||||
TransportStatusDetail::Unwrap(const Status& status) {
|
||||
std::shared_ptr<StatusDetail> detail = status.detail();
|
||||
if (!detail) return std::nullopt;
|
||||
if (detail->type_id() != kTypeId) return std::nullopt;
|
||||
return std::cref(arrow::internal::checked_cast<const TransportStatusDetail&>(*detail));
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
随后我们便可以通过这样调用,提取出Status中实际的TransportStatusDetail。
|
||||
|
||||
```cpp
|
||||
Status status(transportDetail);
|
||||
auto result = Unwrap(status);
|
||||
```
|
||||
|
||||
下面来从几个方面看看,最后给出整个Demo代码。
|
||||
|
||||
### 1. std::cref:创建常量引用
|
||||
|
||||
`std::cref` 是一个模板函数,用于创建对常量对象的引用。它返回一个 `std::reference_wrapper` 对象,可以在需要引用的地方使用。这在函数参数传递中特别有用,因为它允许我们在不进行拷贝的情况下传递常量对象,同时保持引用的语义。
|
||||
|
||||
**示例:**
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <functional>
|
||||
|
||||
void printValue(const int& value) {
|
||||
std::cout << "Value: " << value << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int number = 42;
|
||||
auto crefNumber = std::cref(number);
|
||||
|
||||
printValue(crefNumber); // 使用常量引用传递参数
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### 2. std::ref:创建可修改的引用
|
||||
|
||||
与 `std::cref` 不同,`std::ref` 是一个模板函数,用于创建对可修改对象的引用。它返回一个 `std::reference_wrapper` 对象,允许我们在需要引用的地方使用,同时允许修改被引用的对象。
|
||||
|
||||
**示例:**
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <functional>
|
||||
|
||||
void modifyValue(int& value) {
|
||||
value *= 2;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int number = 42;
|
||||
auto refNumber = std::ref(number);
|
||||
|
||||
modifyValue(refNumber); // 使用可修改的引用作为参数
|
||||
|
||||
std::cout << "Modified Value: " << number << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. std::reference_wrapper:引用的包装器
|
||||
|
||||
`std::reference_wrapper` 是一个模板类,用于包装引用,使其能够在容器中存储或以引用的形式传递。它提供类似引用的语法,并且可以与标准容器一起使用,因为容器无法直接存储引用。
|
||||
|
||||
**示例:**
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
|
||||
int main() {
|
||||
int number1 = 42;
|
||||
int number2 = 73;
|
||||
|
||||
std::vector<std::reference_wrapper<int>> numbers = {std::ref(number1), std::ref(number2)};
|
||||
|
||||
for (auto& num : numbers) {
|
||||
num.get() += 10; // 修改原始对象的值
|
||||
}
|
||||
|
||||
std::cout << "Number 1: " << number1 << std::endl;
|
||||
std::cout << "Number 2: " << number2 << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
在这个示例中,`std::reference_wrapper` 允许我们将引用包装在容器中,然后通过 `get()` 方法来访问和修改原始对象的值。
|
||||
|
||||
## 4.Unwrap Demo
|
||||
|
||||
这里给出具体的代码段,其完整代码参见知识星球内容。
|
||||
|
||||
```cpp
|
||||
std::optional<std::reference_wrapper<const TransportStatusDetail>> Unwrap(const Status& status) {
|
||||
std::shared_ptr<StatusDetail> detail = status.detail();
|
||||
if (!detail) return std::nullopt;
|
||||
if (detail->type_id() != kTypeId) return std::nullopt;
|
||||
return std::cref(static_cast<const TransportStatusDetail&>(*detail));
|
||||
}
|
||||
|
||||
int main() {
|
||||
// 创建 TransportStatusDetail 对象
|
||||
std::shared_ptr<StatusDetail> transportDetail = std::make_shared<TransportStatusDetail>();
|
||||
|
||||
// 创建 Status 对象并传入 TransportStatusDetail 对象
|
||||
Status status(transportDetail);
|
||||
|
||||
auto result = Unwrap(status);
|
||||
|
||||
if (result) {
|
||||
const TransportStatusDetail& detail = result.value().get();
|
||||
// 使用 detail 进行操作
|
||||
std::cout << "TransportStatusDetail found." << std::endl;
|
||||
} else {
|
||||
std::cout << "No valid TransportStatusDetail found." << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
欢迎一起探讨C++那些事,更多项目/内容,欢迎加入知识星球。
|
||||
51
site_extras/cpp-things-tail-recursion-cpp.md
Normal file
51
site_extras/cpp-things-tail-recursion-cpp.md
Normal file
@@ -0,0 +1,51 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/tail-recursion-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 尾递归
|
||||
|
||||
尾递归优化是一种特殊的优化技术,适用于递归函数,它可以极大地减少递归调用的栈空间占用。通过尾递归优化,编译器可以在执行尾递归时避免创建新的栈帧,直接复用当前的栈帧,从而降低栈溢出的风险,并提高性能。
|
||||
|
||||
[TOC]
|
||||
|
||||
### 什么是尾递归?
|
||||
递归调用在返回时,**没有其他操作**需要执行,这样的递归称为**尾递归**。在这种情况下,编译器可以用一个循环结构替代递归,避免多次函数调用的开销。
|
||||
|
||||
### 非尾递归的例子(斐波那契数列)
|
||||
你提供的 `fibonacci_non_tail()` 函数是一个标准的非尾递归实现:
|
||||
|
||||
```cpp
|
||||
int fibonacci_non_tail(int n) {
|
||||
if (n <= 1) {
|
||||
return n;
|
||||
}
|
||||
return fibonacci_non_tail(n - 1) + fibonacci_non_tail(n - 2);
|
||||
}
|
||||
```
|
||||
|
||||
在这个实现中,递归调用 `fibonacci_non_tail(n - 1)` 和 `fibonacci_non_tail(n - 2)` 之后,还需要将它们的结果相加,因此这不是尾递归。每次调用都需要保存上下文信息,以便在递归返回后继续计算,这导致栈空间快速增长。
|
||||
|
||||
### 尾递归优化的示例
|
||||
`fibonacci_tail()` 使用了尾递归的方式:
|
||||
|
||||
```cpp
|
||||
int fibonacci_tail_helper(int n, int a, int b) {
|
||||
if (n == 0) {
|
||||
return a;
|
||||
}
|
||||
return fibonacci_tail_helper(n - 1, b, a + b);
|
||||
}
|
||||
|
||||
int fibonacci_tail(int n) {
|
||||
return fibonacci_tail_helper(n, 0, 1);
|
||||
}
|
||||
```
|
||||
|
||||
这里的 `fibonacci_tail_helper()` 是尾递归。你可以看到,递归调用 `fibonacci_tail_helper(n - 1, b, a + b)` 后,函数不再需要做任何其他工作,直接返回递归调用的结果。因此,递归调用位于函数的“尾部”,没有额外的操作需要在递归调用后执行。
|
||||
|
||||
### 尾递归优化的优势
|
||||
- **减少栈空间使用**:由于不需要保存递归调用的上下文,编译器可以复用栈帧,避免栈空间膨胀。
|
||||
- **防止栈溢出**:尾递归优化允许递归深度达到非常大的值而不会发生栈溢出。
|
||||
- **更高效**:在支持尾递归优化的编译器中,尾递归的性能接近于迭代实现,消除了递归函数调用的开销。
|
||||
|
||||
### 性能测试
|
||||
|
||||
最后针对上面做了一个benchmark,发现尾递归优化在这个场景下非常有用,可以看到性能的差异很大!
|
||||
45
site_extras/cpp-things-vector-resize-reverse.md
Normal file
45
site_extras/cpp-things-vector-resize-reverse.md
Normal file
@@ -0,0 +1,45 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-things/vector-resize-reverse/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ vector resize 与 reverse
|
||||
|
||||
在C++中,`resize`和`reserve`是用于容器(例如`std::vector`)的两个成员函数,用于管理vector的大小和内存分配。
|
||||
|
||||
例如:
|
||||
|
||||
```
|
||||
std::vector<int> v1;
|
||||
v1.resize(1000); //allocation + instance creation
|
||||
cout <<(v1.size() == 1000)<< endl; //prints 1
|
||||
cout <<(v1.capacity()==1000)<< endl; //prints 1
|
||||
|
||||
std::vector<int> v2;
|
||||
v2.reserve(1000); //only allocation
|
||||
cout <<(v2.size() == 1000)<< endl; //prints 0
|
||||
cout <<(v2.capacity()==1000)<< endl; //prints 1
|
||||
```
|
||||
|
||||
`resize`函数用于更改容器的大小,可以增加或减少容器中元素的数量。当增加容器的大小时,新添加的元素将会进行初始化。当减少容器的大小时,超出新大小的元素将会被移除。
|
||||
|
||||
`reserve`函数用于预分配容器的内存空间,但不改变容器的大小。它可以用于提前分配足够的内存,以避免频繁的重新分配内存操作,从而提高性能。但是,调用`reserve`并不会改变容器的大小,只是为容器分配足够的内存空间。
|
||||
|
||||
需要注意的是,`resize`和`reserve`函数在容器类型上的可用性有所不同。`resize`函数对于大多数容器类型是可用的,而`reserve`函数只对具有动态大小的容器类型有效,例如`std::vector`和`std::deque`。对于固定大小的容器类型(例如`std::array`),调用`reserve`没有任何效果。
|
||||
|
||||
从源码层面上来看:
|
||||
|
||||
```
|
||||
void resize(size_type new_size, value_type value = value_type()) {
|
||||
if (new_size < size()) {
|
||||
erase(begin() + new_size, end()); // 移除超出新大小的元素
|
||||
} else {
|
||||
insert(end(), new_size - size(), value); // 添加新元素
|
||||
}
|
||||
}
|
||||
void reserve(size_type _n) {
|
||||
if (__n > max_size())
|
||||
__throw_length_error(__N("vector::reserve"));
|
||||
if (capacity() < __n)
|
||||
_M_reallocate(__n);
|
||||
}
|
||||
```
|
||||
|
||||
> 本节完
|
||||
61
site_extras/cpp-tools-bazel-build-guide.md
Normal file
61
site_extras/cpp-tools-bazel-build-guide.md
Normal file
@@ -0,0 +1,61 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/bazel-build-guide/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Bazel 构建 C++ 项目
|
||||
|
||||
```
|
||||
gpadmin@gpadmin:~$ ./bazel-6.1.1-installer-linux-x86_64.sh --user
|
||||
Bazel installer
|
||||
---------------
|
||||
|
||||
Bazel is bundled with software licensed under the GPLv2 with Classpath exception.
|
||||
You can find the sources next to the installer on our release page:
|
||||
https://github.com/bazelbuild/bazel/releases
|
||||
|
||||
#
|
||||
|
||||
## Build information
|
||||
- [Commit](https://github.com/bazelbuild/bazel/commit/1a90fe5)
|
||||
Uncompressing......WARNING: Invoking Bazel in batch mode since it is not invoked from within a workspace (below a directory having a WORKSPACE file).
|
||||
Extracting Bazel installation...
|
||||
.
|
||||
|
||||
Bazel is now installed!
|
||||
|
||||
Make sure you have "/home/gpadmin/bin" in your path.
|
||||
|
||||
For bash completion, add the following line to your :
|
||||
source /home/gpadmin/.bazel/bin/bazel-complete.bash
|
||||
|
||||
For fish shell completion, link this file into your
|
||||
/home/gpadmin/.config/fish/completions/ directory:
|
||||
ln -s /home/gpadmin/.bazel/bin/bazel.fish /home/gpadmin/.config/fish/completions/bazel.fish
|
||||
|
||||
See http://bazel.build/docs/getting-started.html to start a new project!
|
||||
```
|
||||
|
||||
|
||||
|
||||
默认安装到home/bin
|
||||
|
||||
|
||||
|
||||
```
|
||||
gpadmin@gpadmin:~$ ls ~/bin/
|
||||
bazel
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
1. 在安装过程中,Bazel 可能会提示您添加环境变量。如果是这样,请根据提示编辑您的 `~/.bashrc` 文件并将以下行添加到文件末尾:
|
||||
|
||||
```
|
||||
复制代码export PATH="$PATH:$HOME/bin"
|
||||
```
|
||||
|
||||
1. 重新加载 `.bashrc` 文件以使更改生效:
|
||||
|
||||
```
|
||||
复制代码source ~/.bashrc
|
||||
```
|
||||
36
site_extras/cpp-tools-bazel-debugging.md
Normal file
36
site_extras/cpp-tools-bazel-debugging.md
Normal file
@@ -0,0 +1,36 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/bazel-debugging/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Bazel 与 LLDB 联合调试
|
||||
|
||||
今天在调试时发现通过bazel编译出来的文件在mac上没法调试了,竟然全是汇编代码。
|
||||
|
||||
```
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
|
||||
frame #0: 0x0000000100000fd0 hello_world`main
|
||||
hello_world`main:
|
||||
-> 0x100000fd0 <+0>: pushq %rbp
|
||||
0x100000fd1 <+1>: movq %rsp, %rbp
|
||||
0x100000fd4 <+4>: subq $0x60, %rsp
|
||||
0x100000fd8 <+8>: movl $0x0, -0x4(%rbp)
|
||||
(lldb) quit
|
||||
```
|
||||
|
||||
如何解决呢?
|
||||
|
||||
默认是standalone,我们需要disable,这里采用local,这意味着输出将与其依赖项链接,而不是采用默认的`standalone`策略。
|
||||
|
||||
```cpp
|
||||
build --spawn_strategy=local
|
||||
```
|
||||
|
||||
这样的话可以看到代码了。
|
||||
|
||||
```cpp
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
|
||||
frame #0: 0x0000000100000fdf hello_world`main at hello_world.cc:14:21
|
||||
11
|
||||
12 int main() {
|
||||
13 // Create a thread pool
|
||||
-> 14 auto threadPool = GetCpuThreadPool();
|
||||
15 if (!threadPool) {
|
||||
```
|
||||
97
site_extras/cpp-tools-cmake-essentials.md
Normal file
97
site_extras/cpp-tools-cmake-essentials.md
Normal file
@@ -0,0 +1,97 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/cmake-essentials/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# CMake 入门与实战
|
||||
|
||||
## CMake常用必备一
|
||||
|
||||
[TOC]
|
||||
|
||||
## 1.设置编译器flags
|
||||
|
||||
例如:设置C++标准,显示所有警告。
|
||||
|
||||
```cpp
|
||||
set(CMAKE_CXX_FLAGS "-std=c++0x -Wall")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -Wall")
|
||||
add_compile_options("$<$<STREQUAL:$<TARGET_PROPERTY:LINKER_LANGUAGE>,CXX>:-std=c++11>")
|
||||
```
|
||||
|
||||
还可以设置一些优化flags
|
||||
|
||||
官方资料:https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
-O0, -O1, -O2, -O3
|
||||
```
|
||||
|
||||
如果使用llvm,则可以参考这里:
|
||||
|
||||
> https://clang.llvm.org/docs/DiagnosticsReference.html
|
||||
|
||||
## 2.设置源文件属性
|
||||
|
||||
这是CMake的一个复杂属性,如果存在多个目标,可能需要更改一个目标的某些行为。例如,如果要使用C++11构建main.cpp,而只构建库,则可能希望将其构建为C++14。在这种情况下,您可以使用`set_source_files_properties`命令来配置特定源文件的属性,如下所示:
|
||||
|
||||
```
|
||||
cmakeCopy code
|
||||
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/*.cpp PROPERTIES COMPILE_FLAGS "-std=c++11")
|
||||
```
|
||||
|
||||
可以从以下手册中查看大量的属性,每个属性都可以用于满足您的特定需求。
|
||||
|
||||
- [CMake 属性](https://cmake.org/cmake/help/v3.3/manual/cmake-properties.7.html#source-file-properties)
|
||||
|
||||
> https://cmake.org/cmake/help/v3.3/manual/cmake-properties.7.html#source-file-properties
|
||||
|
||||
## 3.链接器标志
|
||||
|
||||
以下是GNU GCC链接器的链接器标志列表。
|
||||
|
||||
[GNU GCC 链接选项](https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html)
|
||||
|
||||
> https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html
|
||||
|
||||
GCC链接器默认情况下可以在环境变量中定义的目录(/usr/lib;/usr/local/lib)中搜索,然后默认链接标准库。
|
||||
|
||||
最常见的标志之一是`-l`,用于链接所需的库,如`-lzlib`、`-lboost`等。
|
||||
|
||||
还有其他附加标志,可帮助您更改可执行文件的链接选项行为。
|
||||
|
||||
以下是您可以添加链接器标志的变量:
|
||||
|
||||
- `CMAKE_EXE_LINKER_FLAGS`:在创建可执行文件时由链接器使用的标志
|
||||
- `CMAKE_EXE_LINKER_FLAGS_RELEASE`:在创建发布版本可执行文件时由链接器使用的标志
|
||||
- `CMAKE_EXE_LINKER_FLAGS_DEBUG`:在创建调试版本可执行文件时由链接器使用的标志
|
||||
- `CMAKE_STATIC_LINKER_FLAGS`:在创建静态库(.a、.lib)时由链接器使用的标志
|
||||
- `CMAKE_SHARED_LINKER_FLAGS`:在创建共享库(.so、.dll)时由链接器使用的标志
|
||||
- `CMAKE_MODULE_LINKER_FLAGS`:在创建模块库时由链接器使用的标志
|
||||
|
||||
例如,您可以使用以下代码添加链接器标志:
|
||||
|
||||
```
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl")
|
||||
```
|
||||
|
||||
了解如何使用这些标志可以帮助您更好地控制可执行文件的链接行为。
|
||||
|
||||
## 4.Debug与Release包
|
||||
|
||||
在CMakeLists.txt文件内部,可以访问CMAKE_BUILD_TYPE。你可以在CMakeLists.txt中轻松检查构建类型:
|
||||
|
||||
```cpp
|
||||
if(${CMAKE_BUILD_TYPE} MATCHES Debug)
|
||||
message("Debug Build")
|
||||
elseif(${CMAKE_BUILD_TYPE} MATCHES Release)
|
||||
message("Release Build")
|
||||
endif()
|
||||
```
|
||||
|
||||
您还可以使用上一节中所示的配置变量,分别为不同的构建类型设置编译器和链接器标志:
|
||||
|
||||
- CMAKE_EXE_LINKER_FLAGS_RELEASE:用于创建发布版本可执行文件的标志
|
||||
- CMAKE_EXE_LINKER_FLAGS_DEBUG:用于创建调试版本可执行文件的标志
|
||||
- CMAKE_CXX_FLAGS_RELEASE
|
||||
- CMAKE_CXX_FLAGS_DEBUG
|
||||
210
site_extras/cpp-tools-conan-package-manager.md
Normal file
210
site_extras/cpp-tools-conan-package-manager.md
Normal file
@@ -0,0 +1,210 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/conan-package-manager/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Conan C++ 包管理入门
|
||||
|
||||
## 1.Conan安装
|
||||
|
||||
```
|
||||
pip3 install conan
|
||||
```
|
||||
|
||||
## 2.安装第三方库
|
||||
|
||||
安装第三方库时,我们通常需要知道安装的库版本,那么conan提供了相应的搜索命令,列出相应库的版本。
|
||||
|
||||
```
|
||||
conan search gtest --remote=conancenter
|
||||
```
|
||||
|
||||
如果直接搜会报错,conancenter找不到,所以第一步设置remote。
|
||||
|
||||
```
|
||||
conan remote add conancenter https://center.conan.io
|
||||
```
|
||||
|
||||
随后,我们再继续上面的搜索命令,发现报错:
|
||||
|
||||
```cpp
|
||||
ERROR: HTTPSConnectionPool(host='center.conan.io', port=443): Max retries exceeded with url: /v1/ping (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)'),))
|
||||
|
||||
Unable to connect to conancenter=https://center.conan.io
|
||||
1. Make sure the remote is reachable or,
|
||||
2. Disable it by using conan remote disable,
|
||||
Then try again.
|
||||
```
|
||||
|
||||
此时,需要配置证书
|
||||
|
||||
```
|
||||
conan config install https://github.com/conan-io/conanclientcert.git
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
Trying to clone repo: https://github.com/conan-io/conanclientcert.git
|
||||
Repo cloned!
|
||||
Copying file LICENSE to /home/light/.conan/.
|
||||
Copying file cacert.pem to /home/light/.conan/.
|
||||
```
|
||||
|
||||
随后,继续使用`conan search`,我们找到:
|
||||
|
||||
```cpp
|
||||
[light@i-fu3d01tc build]$ conan search gtest --remote=conancenter
|
||||
Existing package recipes:
|
||||
|
||||
gtest/cci.20210126
|
||||
gtest/1.8.1
|
||||
gtest/1.10.0
|
||||
gtest/1.11.0
|
||||
gtest/1.12.1
|
||||
gtest/1.13.0
|
||||
gtest/1.14.0
|
||||
```
|
||||
|
||||
## 3.编写一个项目
|
||||
|
||||
接下来,使用conan编写一个项目。
|
||||
|
||||
项目背景:在开发阶段,我们需要进行单元测试,例如:除法需要测试除以0与非零等边界的断言,我们需要引入第三方库,这里用gtest。
|
||||
|
||||
1.编写代码
|
||||
|
||||
```cpp
|
||||
#include <gtest/gtest.h>
|
||||
double divide(double a, double b) { return b == 0 ? 0 : a / b; }
|
||||
|
||||
TEST(Div, NonZero) {
|
||||
double expected = 1.5;
|
||||
double actual = divide(3, 2);
|
||||
ASSERT_EQ(expected, actual);
|
||||
}
|
||||
|
||||
TEST(Div, Zero) {
|
||||
double expected = 0;
|
||||
double actual = divide(3, 0);
|
||||
ASSERT_EQ(expected, actual);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
2.编写conanfile.txt,指定一个gtest版本。
|
||||
|
||||
```
|
||||
[requires]
|
||||
gtest/1.13.0
|
||||
|
||||
[generators]
|
||||
cmake
|
||||
```
|
||||
|
||||
3.添加CMakeLists.txt,内容很简单:其中感叹号部分需要注意。
|
||||
|
||||
```cpp
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(MultiplyTest LANGUAGES CXX)
|
||||
|
||||
enable_testing()
|
||||
|
||||
// !!!
|
||||
find_package(GTest REQUIRED)
|
||||
|
||||
add_executable(div_test div_test.cpp)
|
||||
|
||||
// !!!
|
||||
target_link_libraries(div_test
|
||||
PRIVATE
|
||||
GTest::GTest)
|
||||
|
||||
add_test(div_gtest div_test)
|
||||
|
||||
```
|
||||
|
||||
4.开始安装与编译
|
||||
|
||||
- 安装第三方库
|
||||
|
||||
```
|
||||
[gpadmin@i-fu3d01tc build]$ conan install ../
|
||||
Configuration:
|
||||
[settings]
|
||||
arch=x86_64
|
||||
arch_build=x86_64
|
||||
build_type=Release
|
||||
compiler=gcc
|
||||
compiler.libcxx=libstdc++11
|
||||
compiler.version=10
|
||||
os=Linux
|
||||
os_build=Linux
|
||||
[options]
|
||||
[build_requires]
|
||||
[env]
|
||||
|
||||
gtest/1.13.0: Not found in local cache, looking in remotes...
|
||||
gtest/1.13.0: Trying with 'conan-public'...
|
||||
gtest/1.13.0: Trying with 'conancenter'...
|
||||
Downloading conanmanifest.txt completed [0.10k]
|
||||
Downloading conanfile.py completed [8.27k]
|
||||
Downloading conan_export.tgz completed [0.32k]
|
||||
Decompressing conan_export.tgz completed [0.00k]
|
||||
gtest/1.13.0: Downloaded recipe revision 8a0bc5b3e159ed45de97260c2bff65b5
|
||||
conanfile.txt: Installing package
|
||||
Requirements
|
||||
gtest/1.13.0 from 'conancenter' - Downloaded
|
||||
Packages
|
||||
gtest/1.13.0:e019a06362b932ca5d1b082b6c112aa150c88de4 - Download
|
||||
|
||||
Installing (downloading, building) binaries...
|
||||
gtest/1.13.0: Retrieving package e019a06362b932ca5d1b082b6c112aa150c88de4 from remote 'conancenter'
|
||||
Downloading conanmanifest.txt completed [3.07k]
|
||||
Downloading conaninfo.txt completed [0.60k]
|
||||
Downloading conan_package.tgz completed [487.88k]
|
||||
Decompressing conan_package.tgz completed [0.00k]
|
||||
gtest/1.13.0: Package installed e019a06362b932ca5d1b082b6c112aa150c88de4
|
||||
gtest/1.13.0: Downloaded package revision 81bd558bf2388a3aee4ee13b8a902a45
|
||||
conanfile.txt: Generator txt created conanbuildinfo.txt
|
||||
conanfile.txt: Generator cmake created conanbuildinfo.cmake
|
||||
conanfile.txt: Aggregating env generators
|
||||
conanfile.txt: Generated conaninfo.txt
|
||||
conanfile.txt: Generated graphinfo
|
||||
```
|
||||
|
||||
- 编译
|
||||
|
||||
```cpp
|
||||
[light@i-fu3d01tc build]$ cmake ..
|
||||
-- The CXX compiler identification is GNU 10.2.1
|
||||
-- Detecting CXX compiler ABI info
|
||||
-- Detecting CXX compiler ABI info - done
|
||||
-- Check for working CXX compiler: /opt/rh/devtoolset-10/root/usr/bin/c++ - skipped
|
||||
-- Detecting CXX compile features
|
||||
-- Detecting CXX compile features - done
|
||||
-- Found GTest: /usr/lib64/libgtest.so
|
||||
-- Configuring done
|
||||
-- Generating done
|
||||
-- Build files have been written to: /home/light/cmake-google-tests/conan/build
|
||||
[light@i-fu3d01tc build]$ make
|
||||
Scanning dependencies of target div_test
|
||||
[ 50%] Building CXX object CMakeFiles/div_test.dir/div_test.cpp.o
|
||||
[100%] Linking CXX executable div_test
|
||||
[100%] Built target div_test
|
||||
```
|
||||
|
||||
- 运行
|
||||
|
||||
```
|
||||
[light@i-fu3d01tc build]$ ./div_test
|
||||
[==========] Running 2 tests from 1 test case.
|
||||
[----------] Global test environment set-up.
|
||||
[----------] 2 tests from Div
|
||||
[ RUN ] Div.NonZero
|
||||
[ OK ] Div.NonZero (0 ms)
|
||||
[ RUN ] Div.Zero
|
||||
[ OK ] Div.Zero (0 ms)
|
||||
[----------] 2 tests from Div (0 ms total)
|
||||
|
||||
[----------] Global test environment tear-down
|
||||
[==========] 2 tests from 1 test case ran. (0 ms total)
|
||||
[ PASSED ] 2 tests.
|
||||
```
|
||||
81
site_extras/cpp-tools-gcc-flags-guide.md
Normal file
81
site_extras/cpp-tools-gcc-flags-guide.md
Normal file
@@ -0,0 +1,81 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/gcc-flags-guide/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# GCC 编译选项详解
|
||||
|
||||
大家经常在编译代码时通常会使用一些gcc flags,今天这篇文章来梳理一下一些比较重要的gcc flag。
|
||||
|
||||
## 1.优化flag
|
||||
|
||||
优化标志用于提高编译代码的性能。这些标志可以加速编译过程并生成高效的程序。
|
||||
|
||||
一些常用的优化标志包括:
|
||||
|
||||
`-O1`、`-O2`、`-O3`、`-Os`:这些标志控制应用的优化级别。
|
||||
|
||||
`-O1`应用基本优化,而`-O2`和`-O3`提供更高级的优化。-Os优化代码大小。
|
||||
|
||||
`-finline-functions`、`-funroll-loops`:这些标志分别控制函数内联和循环展开优化,旨在消除函数调用开销并减少循环迭代。
|
||||
|
||||
## 2.调试Flag
|
||||
|
||||
调试标志有助于提供额外信息,使调试工具能够跟踪和分析代码。
|
||||
|
||||
一些常用的调试标志包括:
|
||||
|
||||
`-g`:该标志在编译后的可执行文件中包含调试符号。
|
||||
|
||||
`-ggdb`:该标志使GCC以适用于GNU调试器(GDB)的格式生成调试信息。
|
||||
|
||||
## 3.警告Flag
|
||||
|
||||
警告标志有助于识别潜在问题、编码错误或代码中存在问题的实践。通过启用警告标志,编译器会对这些情况提供警告,使开发人员能够提高代码质量。
|
||||
|
||||
一些常用的警告标志包括:
|
||||
|
||||
`-Wall`:该标志启用一套全面的警告,涵盖各种潜在问题。
|
||||
|
||||
`-Werror`:该标志将警告视为错误,使编译器在遇到警告时停止编译过程。
|
||||
|
||||
## 4.预处理器Flag
|
||||
|
||||
预处理器标志负责处理源代码中以#开头的指令。这些标志定义宏并控制编译。
|
||||
|
||||
一些常用的预处理器标志包括:
|
||||
|
||||
`-D`:该标志用于在编译过程中定义宏。例如,`-DDEBUG`可用于定义DEBUG宏,根据其是否存在启用条件编译。
|
||||
|
||||
`-I`:该标志用于指定头文件位于的额外目录。它帮助预处理器在编译代码时找到必要的头文件。
|
||||
|
||||
## 5.链接器Flag
|
||||
|
||||
链接器标志控制链接过程,该过程在编译后进行,将目标文件和库组合以生成最终的可执行文件。
|
||||
|
||||
一些常用的链接器标志包括:
|
||||
|
||||
`-l`:该标志用于链接外部库。例如:`-lpthread`链接POSIX线程库。
|
||||
|
||||
`-L`:该标志用于指定库位于的额外目录。它帮助链接器在链接过程中找到所需的库。
|
||||
|
||||
## 6.平台特定flag
|
||||
|
||||
GCC提供了针对特定平台的标志,允许开发人员针对特定架构或启用特定平台功能。在为特定硬件或操作系统开发代码时,这些标志非常有用。
|
||||
|
||||
平台特定标志包括:
|
||||
|
||||
`-march`:该标志指定目标架构。例如,`-march=native`指示GCC优化为主机机器的架构。
|
||||
|
||||
`-m32`和`-m64`:这些标志指定是为32位还是64位目标进行编译。
|
||||
|
||||
## 7.其他Flag
|
||||
|
||||
除了前面提到的类别,还有一些其他标志。
|
||||
|
||||
一些常用的杂项标志包括:
|
||||
|
||||
`-std`:该标志指定要使用的C语言标准版本。例如,`-std=c99`选择C99标准。 `-pedantic`:该标志启用对所选择的C语言标准的严格遵守,对非标准或可疑代码结构提供额外的警告。 `-Wextra`:该标志启用超过-Wall启用的额外警告,提供更全面的代码分析。
|
||||
|
||||
需要注意的是,标志的可用性和功能可能会因GCC的不同版本和平台而有所变化。因此,建议查阅GCC文档和相关资源,获取有关特定标志及其用法的详细信息。
|
||||
|
||||
完整文档地址:
|
||||
|
||||
> https://gcc.gnu.org/onlinedocs/gcc/
|
||||
34
site_extras/cpp-tools-gdb-debugging-guide.md
Normal file
34
site_extras/cpp-tools-gdb-debugging-guide.md
Normal file
@@ -0,0 +1,34 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/gdb-debugging-guide/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# GDB 调试 C++ 程序
|
||||
|
||||
当使用GNU Debugger(GDB)调试C代码时,你会发现它是UNIX系统上最受欢迎的调试器,用于调试C和C++程序。下面是一个简明易懂的使用GDB调试C代码的解释:
|
||||
|
||||
首先,在命令行中切换到包含代码的当前文件夹,并运行以下命令:
|
||||
|
||||
gcc -g -Wall code.c -o output
|
||||
|
||||
其中,`-g`选项对于使用GDB工具是必要的。`-Wall`选项用于显示警告信息。这将创建一个名为"output"的可执行文件。
|
||||
|
||||
然后,运行以下命令打开GDB对话框并从output文件中获取符号信息(或简单地说,设置整个环境以调试code.c):
|
||||
|
||||
gdb output
|
||||
|
||||
使用以下命令可以帮助你进行调试:
|
||||
|
||||
- `list`:列出源代码。
|
||||
- `b x`:在x处设置断点。x可以是模块的名称或行号。例如,x可以是main等函数名称。
|
||||
- `r`:执行程序(直到断点),并提供结果。即,在断点处运行代码并生成结果。[如果有参数,则为r 参数1 参数2 参数3 ...]
|
||||
- `info breakpoints x`:给出断点x的详细信息。
|
||||
- `info breakpoints`:给出所有断点的详细信息。
|
||||
- `delete x`:删除断点x。
|
||||
- `disable x`和`enable x`:禁用和启用断点x。
|
||||
- `print p`:打印变量p的值。
|
||||
- `display p`:在每次运行后显示变量p的值(自动化整个过程)。
|
||||
- `c`:继续执行程序(跳过for循环等迭代)。使用`c-iter1`跳过第一次迭代,再次输入`c`跳过第二次迭代,依此类推。
|
||||
- 你还可以使用额外的条件,例如`b x if (y > m)`,意思是如果y的值大于m,则在第x行处设置断点。
|
||||
- GDB还可以在多个文件中设置断点。例如,如果program.c中调用了function.c中的一个函数,你可以使用`b function.c:x`在function.c的第x行设置断点。
|
||||
- `bt`:用于回溯代码执行的路径。`bt`会给出一个索引列表,显示代码经过的进程。例如:#0 进程0的描述,#1 进程1的描述,依此类推。其中,0是最近的进程。
|
||||
- 输入`f x`将跳转到进程x(`f 0`将跳转到进程0),并给出对应函数执行时的变量值。
|
||||
- `s`:用于进入函数并获取更多详细信息。
|
||||
- `next`:用于逐行执行代码。
|
||||
122
site_extras/cpp-tools-gdb-python-enhancement.md
Normal file
122
site_extras/cpp-tools-gdb-python-enhancement.md
Normal file
@@ -0,0 +1,122 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/gdb-python-enhancement/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# GDB Python 扩展调试
|
||||
|
||||
## 0.导语
|
||||
|
||||
调试是软件开发过程中不可或缺的一环,而GDB(GNU调试器)作为一款功能强大的调试工具,在开发者中得到广泛应用。除了传统的命令行调试功能外,GDB还提供了Python的GDB库,允许开发者使用Python语言扩展和增强调试的能力。本文将介绍如何在GDB中使用Python的GDB库,展示其强大的调试功能和用例。
|
||||
|
||||
开始之前,确保已经正确安装Python和GDB,并且Python版本与GDB兼容。然后,按照以下步骤安装Python的GDB库:
|
||||
|
||||
a. 在命令行中执行`gdb`打开GDB。
|
||||
|
||||
b. 输入`python`命令,进入GDB的Python解释器。
|
||||
|
||||
c. 执行`import gdb`,如果没有报错,说明Python的GDB库已经正确安装。
|
||||
|
||||
```gdb
|
||||
(gdb) python
|
||||
>import gdb
|
||||
>end
|
||||
```
|
||||
|
||||
gdb调试过程中我们通常想查看一些复杂结构变量,例如PostgreSQL中的List结构,啥都能往里面放,里面具体是啥真不好直观打印出来,此时在我们日常开发中就有了python脚本,下面示例:
|
||||
|
||||
```gdb
|
||||
(gdb) tl
|
||||
TargetEntry [resno=1 resname="sum"]
|
||||
Aggref [aggfnoid=2107 aggtype=1700 aggtranstype=2281 aggstar=false aggvariadic=false aggkind=110 'n' agglevelsup=0 aggsplit=AGGSPLIT_FINAL_DESERIAL aggno=0 aggtransno=0 agg_expr_id=0]
|
||||
```
|
||||
|
||||
## 1.Hello python gdb
|
||||
|
||||
我们可以在gdb中执行一些python操作,例如:print,如下所示:
|
||||
|
||||
```
|
||||
scssCopy code
|
||||
(gdb) python
|
||||
> print(1+2)
|
||||
> end
|
||||
3
|
||||
(gdb) end
|
||||
This command cannot be used at the top level.
|
||||
```
|
||||
|
||||
在这个示例中,我们进入GDB的Python解释器,并执行了一个简单的Python语句`print(1+2)`,结果为3。
|
||||
|
||||
另一个例子是我们可以直接输入python xxxx来运行。
|
||||
|
||||
```
|
||||
scssCopy code
|
||||
(gdb) python f = 2
|
||||
(gdb) python print(f)
|
||||
2
|
||||
```
|
||||
|
||||
在这个示例中,我们在GDB中使用Python语句定义了一个变量`f`,并打印了它的值,结果为2。
|
||||
|
||||
## 2.实战:如何编写?
|
||||
|
||||
核心点在于我们如何编写这些脚本?通过这个脚本来方便打印出自己代码,下面是实战环节,关于本节的相关代码与资料将会更新在星球中,欢迎关注:
|
||||
|
||||
|
||||
|
||||
```cpp
|
||||
struct Point {
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
```
|
||||
|
||||
现在有一个Point结构体,我想通过脚本打印出来,如何实现呢?
|
||||
|
||||
逻辑非常简单,读取结构体,然后print即可。
|
||||
|
||||
```python
|
||||
import gdb
|
||||
|
||||
def print_point(point):
|
||||
print(f"Point: x={point['x']}, y={point['y']}")
|
||||
|
||||
def print_person(person):
|
||||
age = person['age']
|
||||
print(f"Person: age={age}")
|
||||
|
||||
class PrintCppStruct(gdb.Command):
|
||||
def __init__(self):
|
||||
super(PrintCppStruct, self).__init__("print_cpp_struct", gdb.COMMAND_USER)
|
||||
|
||||
def invoke(self, arg, from_tty):
|
||||
try:
|
||||
cl = gdb.parse_and_eval(arg)
|
||||
if cl.type.code == gdb.TYPE_CODE_STRUCT and str(cl.type) == 'Point':
|
||||
print_point(cl)
|
||||
elif cl.type.code == gdb.TYPE_CODE_STRUCT and str(cl.type) == 'Person':
|
||||
print_person(cl)
|
||||
else:
|
||||
print("Unknown C++ structure type.")
|
||||
except gdb.error as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
PrintCppStruct()
|
||||
|
||||
```
|
||||
|
||||
如何使用?
|
||||
|
||||
只需要source即可:
|
||||
|
||||
```
|
||||
(gdb) source print.py
|
||||
```
|
||||
|
||||
在这个示例中,我们通过`source`命令在GDB中加载了一个名为`print.py`的Python脚本。
|
||||
|
||||
```cpp
|
||||
(gdb) print_cpp_struct myPoint
|
||||
Point: x=10, y=20
|
||||
```
|
||||
|
||||
在这个示例中,我们在GDB中使用了一个自定义的命令`print_cpp_struct`,它通过Python的GDB库打印了一个名为`myPoint`的C++结构体的值。
|
||||
|
||||
通过在GDB中使用Python的GDB库,开发者可以利用Python的强大功能扩展和增强调试的能力。它提供了丰富的API和灵活的脚本编写能力,使得调试过程更加高效和便捷。无论是自动化调试任务、数据分析和可视化,还是动态修改程序行为,Python的GDB库都为开发者提供了丰富的选择和灵活性。希望本文能够帮助您更好地理解和应用Python的GDB库,提升调试技能和开发效率。
|
||||
224
site_extras/cpp-tools-lldb-debugging.md
Normal file
224
site_extras/cpp-tools-lldb-debugging.md
Normal file
@@ -0,0 +1,224 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/lldb-debugging/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# LLDB 调试 C++ 程序
|
||||
|
||||
[TOC]
|
||||
|
||||
本文将介绍如何使用 LLDB 调试器调试一个简单的 C++ 程序。我们的示例代码命名为 `test.cpp`。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
struct MyStruct {
|
||||
int myInt;
|
||||
std::string myString;
|
||||
};
|
||||
|
||||
int main() {
|
||||
MyStruct myStruct;
|
||||
myStruct.myInt = 42;
|
||||
myStruct.myString = "Hello, world!";
|
||||
|
||||
int sum = 0;
|
||||
for (int i = 1; i <= 5; ++i) {
|
||||
sum += i;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 编译
|
||||
|
||||
首先,我们需要使用 `-g` 标志编译代码以启用额外的调试信息。
|
||||
|
||||
```sh
|
||||
clang++ -g test.cpp -o test
|
||||
```
|
||||
|
||||
## 开始调试
|
||||
|
||||
接着,我们附加调试器。
|
||||
|
||||
```sh
|
||||
lldb test
|
||||
```
|
||||
|
||||
## 断点
|
||||
|
||||
我们将断点设置在 `main()` 函数。
|
||||
|
||||
```sh
|
||||
(lldb) b main
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
Breakpoint 1: where = test`main + 19 at test.cpp:10:14, address = 0x0000000100003be3
|
||||
|
||||
## 运行
|
||||
|
||||
然后,我们启动进程。
|
||||
|
||||
```sh
|
||||
(lldb) run
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
Process 11333 launched: '/Users/light/test' (x86_64)
|
||||
Process 11333 stopped
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
|
||||
frame #0: 0x0000000100003be3 test`main at test.cpp:10:14
|
||||
7 };
|
||||
8
|
||||
9 int main() {
|
||||
-> 10 MyStruct myStruct;
|
||||
11 myStruct.myInt = 42;
|
||||
12 myStruct.myString = "Hello, world!";
|
||||
13
|
||||
```
|
||||
|
||||
## 查看断点
|
||||
|
||||
现在,我们已经停在了 `main()` 函数的开头。我们可以设置在特定行上的断点。
|
||||
|
||||
```sh
|
||||
(lldb) b 16
|
||||
```
|
||||
|
||||
输出:Breakpoint 2: where = test`main + 76 at test.cpp:16:16, address = 0x0000000100003c1c
|
||||
|
||||
要列出当前设置的断点,请使用以下命令。
|
||||
|
||||
```sh
|
||||
(lldb) breakpoint list
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```
|
||||
(lldb) breakpoint list
|
||||
Current breakpoints:
|
||||
1: name = 'main', locations = 1, resolved = 1, hit count = 1
|
||||
1.1: where = test`main + 19 at test.cpp:10:14, address = 0x0000000100003be3, resolved, hit count = 1
|
||||
|
||||
2: file = '/Users/zhangxing/test.cpp', line = 16, exact_match = 0, locations = 1, resolved = 1, hit count = 0
|
||||
2.1: where = test`main + 76 at test.cpp:16:16, address = 0x0000000100003c1c, resolved, hit count = 0
|
||||
```
|
||||
|
||||
## 程序继续运行
|
||||
|
||||
我们可以继续执行程序直到下一个断点。
|
||||
|
||||
```sh
|
||||
(lldb) c
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```
|
||||
Process 11823 resuming
|
||||
Process 11823 stopped
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1
|
||||
frame #0: 0x0000000100003c1c test`main at test.cpp:16:16
|
||||
13
|
||||
14 int sum = 0;
|
||||
15 for (int i = 1; i <= 5; ++i) {
|
||||
-> 16 sum += i;
|
||||
17 }
|
||||
18
|
||||
19 return 0;
|
||||
```
|
||||
|
||||
## 打印变量
|
||||
|
||||
要获取当前局部变量的值,可以使用以下命令:
|
||||
|
||||
```sh
|
||||
(lldb) p myStruct
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```
|
||||
(MyStruct) $0 = (myInt = 42, myString = "Hello, world!")
|
||||
```
|
||||
|
||||
## 观察点
|
||||
|
||||
要监视特定变量的值更改,我们可以使用监视点。
|
||||
|
||||
```sh
|
||||
(lldb) watch set variable sum
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
Watchpoint created: Watchpoint 1: addr = 0x7ffeefbff1e8 size = 4 state = enabled type = w
|
||||
declare @ '/Users/zhangxing/test.cpp:14'
|
||||
watchpoint spec = 'sum'
|
||||
new value: 0
|
||||
```
|
||||
|
||||
当next后,会看到Watchpoint的变化。
|
||||
|
||||
```cpp
|
||||
(lldb) n
|
||||
|
||||
Watchpoint 1 hit:
|
||||
old value: 3
|
||||
new value: 6
|
||||
Process 11823 stopped
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = watchpoint 1
|
||||
frame #0: 0x0000000100003c25 test`main at test.cpp:15:29
|
||||
12 myStruct.myString = "Hello, world!";
|
||||
13
|
||||
14 int sum = 0;
|
||||
-> 15 for (int i = 1; i <= 5; ++i) {
|
||||
16 sum += i;
|
||||
17 }
|
||||
18
|
||||
|
||||
```
|
||||
|
||||
如果想要根据条件停止执行,可以设置停止条件。
|
||||
|
||||
```sh
|
||||
(lldb) watch modify -c '(sum > 5)'
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
Watchpoint 1 hit:
|
||||
new value: 6
|
||||
Process 12848 stopped
|
||||
* thread #1, queue = 'com.apple.main-thread', stop reason = watchpoint 1
|
||||
frame #0: 0x0000000100003c25 test`main at test.cpp:15:29
|
||||
12 myStruct.myString = "Hello, world!";
|
||||
13
|
||||
14 int sum = 0;
|
||||
-> 15 for (int i = 1; i <= 5; ++i) {
|
||||
16 sum += i;
|
||||
17 }
|
||||
18
|
||||
```
|
||||
|
||||
完成调试后,可以继续执行程序。
|
||||
|
||||
```sh
|
||||
(lldb) c
|
||||
```
|
||||
|
||||
如需了解更多信息,请参阅 LLDB 文档:
|
||||
|
||||
- [LLDB 和 GDB 对照指南](https://lldb.llvm.org/lldb-gdb.html)
|
||||
- [LLDB 教程](https://lldb.llvm.org/tutorial.html)
|
||||
|
||||
---
|
||||
|
||||
通过这些步骤,您可以轻松地使用 LLDB 调试您的 C++ 程序,查找错误并解决问题。
|
||||
50
site_extras/cpp-tools-memory-leak-debug-session.md
Normal file
50
site_extras/cpp-tools-memory-leak-debug-session.md
Normal file
@@ -0,0 +1,50 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/memory-leak-debug-session/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 内存泄漏排查实战
|
||||
|
||||
```
|
||||
regression=# SELECT t1.a, t1.c, t2.b, t2.c FROM prt1_e t1, prt2_e t2 WHERE (t1.a + t1.b)/2 = (t2.b + t2.a)/2 AND t1.c = 0 ORDER BY t1.a, t2.b;
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x7cfdd48 in block 0x7cfc580 (seg1 slice1 127.0.1.1:7003 pid=4295)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x7cfc580 (seg1 slice1 127.0.1.1:7003 pid=4295)
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x7cfdd48 in block 0x7cfc580 (seg1 slice1 127.0.1.1:7003 pid=4295)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x7cfc580 (seg1 slice1 127.0.1.1:7003 pid=4295)
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x87f85c8 in block 0x87f6e00 (seg0 slice1 127.0.1.1:7002 pid=4294)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x87f6e00 (seg0 slice1 127.0.1.1:7002 pid=4294)
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x7d3c5c8 in block 0x7d3ae00 (seg2 slice1 127.0.1.1:7004 pid=4296)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x7d3ae00 (seg2 slice1 127.0.1.1:7004 pid=4296)
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x87f85c8 in block 0x87f6e00 (seg0 slice1 127.0.1.1:7002 pid=4294)
|
||||
WARNING: problem in alloc set ExecutorState: bad single-chunk 0x7d3c5c8 in block 0x7d3ae00 (seg2 slice1 127.0.1.1:7004 pid=4296)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x87f6e00 (seg0 slice1 127.0.1.1:7002 pid=4294)
|
||||
WARNING: problem in alloc set ExecutorState: found inconsistent memory block 0x7d3ae00 (seg2 slice1 127.0.1.1:7004 pid=4296)
|
||||
```
|
||||
|
||||
|
||||
|
||||
调试:
|
||||
|
||||
```
|
||||
(gdb) b aset.c:1109 if chunk=0x7cfdd48
|
||||
Breakpoint 1 at 0x105d420: file aset.c, line 1109.
|
||||
(gdb) c
|
||||
Continuing.
|
||||
|
||||
Thread 1 "postgres" hit Breakpoint 1, AllocSetAlloc (context=0x787ac50, size=4096) at aset.c:1109
|
||||
1109 block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ);
|
||||
(gdb) p chunk
|
||||
$1 = (AllocChunk) 0x7cfdd48
|
||||
(gdb) p chunk->size
|
||||
$2 = 9187201950435737471
|
||||
(gdb) p &chunk->size
|
||||
$3 = (Size *) 0x7cfdd48
|
||||
(gdb) watch (*((Size *) 0x7cfdd48))
|
||||
Hardware watchpoint 2: (*((Size *) 0x7cfdd48))
|
||||
(gdb) i b
|
||||
Num Type Disp Enb Address What
|
||||
1 breakpoint keep y 0x000000000105d420 in AllocSetAlloc at aset.c:1109
|
||||
stop only if chunk=0x7cfdd48
|
||||
breakpoint already hit 1 time
|
||||
2 hw watchpoint keep y (*((Size *) 0x7cfdd48))
|
||||
(gdb) d 1
|
||||
(gdb) c
|
||||
|
||||
```
|
||||
384
site_extras/cpp-tools-meson-build.md
Normal file
384
site_extras/cpp-tools-meson-build.md
Normal file
@@ -0,0 +1,384 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/meson-build/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# Meson 构建 C++ 项目
|
||||
|
||||
最近在使用一些开源项目的时候,发现都采用了meson+ninja的构建方式,摒弃了CMake,Makefile的方式,本文将会引入Meson,从入门安装到完整编写一个meson项目。
|
||||
|
||||
下面,我们来进入正文。
|
||||
|
||||
## 1.Meson安装
|
||||
|
||||
> https://github.com/mesonbuild/meson
|
||||
|
||||
Meson 可以通过 PyPi 获得,因此可以使用 pip3 install meson 进行安装。确保在不同系统中使用正确的 pip 命令,务必使用 Python 3 版本的 pip。
|
||||
|
||||
如果希望,也可以使用标准的 Python 命令在本地安装:
|
||||
|
||||
```bash
|
||||
python3 -m pip install meson
|
||||
```
|
||||
|
||||
对于使用 Ninja 进行构建的情况,可以直接从 Ninja GitHub 发布页面或通过 PyPi 下载 Ninja:
|
||||
|
||||
```bash
|
||||
python3 -m pip install ninja
|
||||
```
|
||||
|
||||
有关安装 Meson build 的更多信息,请阅读下方Meson官方网站。
|
||||
|
||||
> https://mesonbuild.com/Getting-meson.html
|
||||
|
||||
## 2.Meson Vs Cmake
|
||||
|
||||
既然大家都用CMake,为何还要用Meson呢,他们各自优劣是什么呢?
|
||||
|
||||
在性能方面,Meson 通常以其快速的构建速度而闻名。Meson 的设计旨在优化构建速度,并且在增量构建方面表现特别出色。Meson 使用 Ninja 构建系统作为默认后端,Ninja 本身也以快速和高效而著称。
|
||||
|
||||
相比之下,CMake 的构建速度可能会受到项目规模的影响,尤其是在较大的项目中。CMake 使用各种生成器(如Makefile),而不同生成器的性能也可能有所不同。
|
||||
|
||||
当然也可以使用CMake + Ninja去提高编译速度。
|
||||
|
||||
从开源项目角度来看Meson,其使用场景也是非常的多,例如:[PostgreSQL](https://www.postgresql.org/)、[QEMU](https://qemu.org/)、[GNOME Software](https://gitlab.gnome.org/GNOME/gnome-software)、[GTK+](https://gitlab.gnome.org/GNOME/gtk),等等
|
||||
|
||||
> https://mesonbuild.com/Users.html
|
||||
|
||||
### 2.1 Meson的优势与劣势
|
||||
|
||||
1.优势
|
||||
|
||||
- 基于Python,使用简单
|
||||
- 支持交叉编译
|
||||
- 所有对象都是强类型的:由于对象是诸如 'dependency'、'include directory' 等实体,因此很难出现字符串替换错误。
|
||||
- 非常方便的引用第三发库
|
||||
- **非常非常快,特别是在增量构建时。**
|
||||
- 文档比cmake好n倍。
|
||||
|
||||
> http://mesonbuild.com
|
||||
|
||||
2.劣势
|
||||
|
||||
- 可能不如CMake成熟
|
||||
- 有Python3 + Ninja的依赖
|
||||
- 项目生成器,IDE支持Meson不如CMake
|
||||
- vscode支持
|
||||
- https://github.com/mesonbuild/vscode-meson
|
||||
- 可用模块有限
|
||||
- 需要自己将非meson项目提交到wrapdb
|
||||
- https://mesonbuild.com/Wrapdb-projects.html
|
||||
|
||||
### 2.2 CMake的优势与劣势
|
||||
|
||||
1.优势
|
||||
|
||||
- IDE支持友好,团队协作比较友
|
||||
- 成熟,几乎成为C++项目的标准
|
||||
|
||||
2.缺点
|
||||
|
||||
- 交叉编译困难
|
||||
- 编译速度相对比较慢
|
||||
|
||||
## 3.Meson WrapDB
|
||||
|
||||
由于googletest不是meson项目,那如何使用meson去依赖它呢?
|
||||
|
||||
同理,grpc、abseil-cpp使用方式类似。
|
||||
|
||||
这里就要先引入WrapDB,Meson WrapDB 是 Meson 构建系统的一个组件,用于管理和提供第三方项目的构建描述文件,通常称为 "wrap" 文件。这些 wrap 文件包含了配置和构建第三方项目所需的信息,以便能够轻松地集成到使用 Meson 构建系统的其他项目中。
|
||||
|
||||
可以通过search命令或者下方网站查询第三方库。
|
||||
|
||||
> https://mesonbuild.com/Wrapdb-projects.html#meson-wrapdb-packages
|
||||
|
||||
我们以gtest使用为例:
|
||||
|
||||
- 搜索gtest
|
||||
|
||||
```
|
||||
meson wrap search gtest
|
||||
```
|
||||
|
||||
如果该命令返回包装的项目名称,那么便可以进行下一步了:
|
||||
|
||||
- 在自己的项目创建subprojects目录,通过install安装gtest
|
||||
|
||||
```
|
||||
mkdir -p subprojects
|
||||
meson wrap install gtest
|
||||
```
|
||||
|
||||
此时你的项目所依赖的第三方库均已在subprojects目录安装好了。
|
||||
|
||||
```cpp
|
||||
➜ gtest_div tree -L 1 subprojects
|
||||
subprojects
|
||||
├── gtest.wrap
|
||||
```
|
||||
|
||||
此时会生成gtest.wrap,里面的内容会包含下面的内容。
|
||||
|
||||
注意:此文件是上方install之后产生的文件,建议不要修改。
|
||||
|
||||
```cpp
|
||||
[wrap-file]
|
||||
directory = googletest-1.14.0
|
||||
source_url = https://github.com/google/googletest/archive/refs/tags/v1.14.0.tar.gz
|
||||
source_filename = gtest-1.14.0.tar.gz
|
||||
source_hash = 8ad598c73ad796e0d8280b082cebd82a630d73e73cd3c70057938a6501bba5d7
|
||||
patch_filename = gtest_1.14.0-1_patch.zip
|
||||
patch_url = https://wrapdb.mesonbuild.com/v2/gtest_1.14.0-1/get_patch
|
||||
patch_hash = 2e693c7d3f9370a7aa6dac802bada0874d3198ad4cfdf75647b818f691182b50
|
||||
source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/gtest_1.14.0-1/gtest-1.14.0.tar.gz
|
||||
wrapdb_version = 1.14.0-1
|
||||
|
||||
[provide]
|
||||
gtest = gtest_dep
|
||||
gtest_main = gtest_main_dep
|
||||
gmock = gmock_dep
|
||||
gmock_main = gmock_main_dep
|
||||
|
||||
```
|
||||
|
||||
## 4.如何编写一个meson项目?
|
||||
|
||||
接下来,来到实践环节,如何编写一个meson项目呢?
|
||||
|
||||
下面以a/b除法测试为例,使用gtest进行单元测试的一个小项目。
|
||||
|
||||
### 4.1 编写代码
|
||||
|
||||
```
|
||||
double divide(double a, double b);
|
||||
```
|
||||
|
||||
.h与.cc放到src目录:
|
||||
|
||||
```cpp
|
||||
src
|
||||
├── division.cc
|
||||
└── division.h
|
||||
```
|
||||
|
||||
随后同级目录创建test目录。
|
||||
|
||||
```cpp
|
||||
test
|
||||
└── division_test.cc
|
||||
```
|
||||
|
||||
### 4.2 meson项目管理
|
||||
|
||||
在项目根路径添加meson.build文件,内容如下:
|
||||
|
||||
```python
|
||||
project('gtest_div', 'cpp')
|
||||
gtest_proj = subproject('gtest')
|
||||
gtest_dep = gtest_proj.get_variable('gtest_main_dep')
|
||||
div_src = files('src/division.cc')
|
||||
tests_src = files('test/division_test.cc')
|
||||
e = executable(
|
||||
'division_test',
|
||||
tests_src + div_src,
|
||||
dependencies : [ gtest_dep],
|
||||
override_options : ['cpp_std=c++14']
|
||||
)
|
||||
# https://mesonbuild.com/Unit-tests.html#testing-tool
|
||||
test('this is a division test', e)
|
||||
```
|
||||
|
||||
可以看到这个内容跟python的语法基本一致,熟悉python的看这个代码就非常容易了,这里着重讲一下上面比较重要的部分。
|
||||
|
||||
- 引入第三方库
|
||||
|
||||
例如:你引入的第三方库的项目叫做gtest,如下:
|
||||
|
||||
```
|
||||
project('gtest', 'cpp',
|
||||
version : '1.14.0',
|
||||
default_options : ['cpp_std=c++14'],
|
||||
license : 'bsd')
|
||||
```
|
||||
|
||||
那么便可以通过subproject获取到这个project,然后通过`gtest_proj.get_variable`便可以获取到gtest的依赖信息,例如:googletest里面是这样声明的:
|
||||
|
||||
```c
|
||||
gtest_main_dep = declare_dependency(
|
||||
include_directories : gtest_incdir,
|
||||
sources : [gtest_libsources, gtest_mainsources],
|
||||
dependencies : dependency('threads')
|
||||
)
|
||||
```
|
||||
|
||||
- executable
|
||||
|
||||
executable跟cmake里面的add_executable非常类似,生成可执行文件division_test。
|
||||
|
||||
- test
|
||||
|
||||
单元测试语法:
|
||||
|
||||
```
|
||||
e = executable('prog', 'testprog.c')
|
||||
test('name of test', e)
|
||||
```
|
||||
|
||||
可以使用`meson test`或者`ninja test`,运行完之后会产生测试日志,位于:
|
||||
|
||||
```
|
||||
build/meson-logs/testlog.txt
|
||||
```
|
||||
|
||||
### 4.3 构建与运行Meson项目
|
||||
|
||||
经过上面的操作,一个meson项目准备就绪。接下来,我们来构建与运行这个项目。
|
||||
|
||||
#### 4.3.1 配置构建目录
|
||||
|
||||
此时类似于cmake的`mkdir build && cmake ..`。
|
||||
|
||||
```cpp
|
||||
meson setup build
|
||||
```
|
||||
|
||||
运行如下:
|
||||
|
||||
```
|
||||
➜ gtest_div meson setup build
|
||||
The Meson build system
|
||||
Version: 1.2.3
|
||||
Source dir: /Users/light/work/practice/gtest_div
|
||||
Build dir: /Users/light/work/practice/gtest_div/build
|
||||
Build type: native build
|
||||
Project name: gtest_div
|
||||
Project version: undefined
|
||||
C++ compiler for the host machine: c++ (clang 12.0.5 "Apple clang version 12.0.5 (clang-1205.0.22.11)")
|
||||
C++ linker for the host machine: c++ ld64 650.9
|
||||
Host machine cpu family: x86_64
|
||||
Host machine cpu: x86_64
|
||||
Downloading gtest source from https://github.com/google/googletest/archive/refs/tags/v1.14.0.tar.gz
|
||||
Download size: 867764
|
||||
Downloading: ..........
|
||||
Downloading gtest patch from https://wrapdb.mesonbuild.com/v2/gtest_1.14.0-1/get_patch
|
||||
Download size: 2440
|
||||
Downloading: ..........
|
||||
|
||||
Executing subproject gtest
|
||||
|
||||
gtest| Project name: gtest
|
||||
gtest| Project version: 1.14.0
|
||||
gtest| C++ compiler for the host machine: c++ (clang 12.0.5 "Apple clang version 12.0.5 (clang-1205.0.22.11)")
|
||||
gtest| C++ linker for the host machine: c++ ld64 650.9
|
||||
gtest| Run-time dependency threads found: YES
|
||||
gtest| Dependency threads found: YES unknown (cached)
|
||||
gtest| Dependency threads found: YES unknown (cached)
|
||||
gtest| Dependency threads found: YES unknown (cached)
|
||||
gtest| Build targets in project: 0
|
||||
gtest| Subproject gtest finished.
|
||||
|
||||
Build targets in project: 1
|
||||
|
||||
gtest_div undefined
|
||||
|
||||
Subprojects
|
||||
gtest: YES
|
||||
|
||||
Found ninja-1.11.1 at /usr/local/bin/ninja
|
||||
```
|
||||
|
||||
此时我们可以在subprojects看到缓存的gtest项目。
|
||||
|
||||
```
|
||||
subprojects
|
||||
├── googletest-1.14.0 # here
|
||||
├── gtest.wrap
|
||||
└── packagecache # here
|
||||
```
|
||||
|
||||
#### 4.3.2 编译
|
||||
|
||||
我们可以使用下面两个命令,第一种:
|
||||
|
||||
```
|
||||
meson compile -C build/
|
||||
```
|
||||
|
||||
运行日志:
|
||||
|
||||
```
|
||||
➜ gtest_div meson compile -C build/
|
||||
INFO: autodetecting backend as ninja
|
||||
INFO: calculating backend command to run: /usr/local/bin/ninja -C /Users/light/work/practice/gtest_div/build
|
||||
ninja: Entering directory `/Users/light/work/practice/gtest_div/build'
|
||||
[5/5] Linking target division_test
|
||||
```
|
||||
|
||||
第二种:
|
||||
|
||||
```
|
||||
➜ gtest_div ninja -C build
|
||||
ninja: Entering directory `build'
|
||||
[5/5] Linking target division_test
|
||||
```
|
||||
|
||||
这两种命令本质是一样,都会用ninja来编译,当然也可以不用`-C`指定目录,那么此时需要`cd build && ninja`或者`cd build && meson compile`。
|
||||
|
||||
#### 4.3.3 运行与测试
|
||||
|
||||
此时会生成上division_test可执行程序,运行如下:
|
||||
|
||||
```
|
||||
➜ gtest_div ./build/division_test
|
||||
Running main() from ../subprojects/googletest-1.14.0/googletest/src/gtest_main.cc
|
||||
[==========] Running 2 tests from 1 test suite.
|
||||
[----------] Global test environment set-up.
|
||||
[----------] 2 tests from DivisionTest
|
||||
[ RUN ] DivisionTest.Divide
|
||||
[ OK ] DivisionTest.Divide (0 ms)
|
||||
[ RUN ] DivisionTest.DivideByZero
|
||||
[ OK ] DivisionTest.DivideByZero (0 ms)
|
||||
[----------] 2 tests from DivisionTest (0 ms total)
|
||||
|
||||
[----------] Global test environment tear-down
|
||||
[==========] 2 tests from 1 test suite ran. (0 ms total)
|
||||
[ PASSED ] 2 tests.
|
||||
```
|
||||
|
||||
由于在meson.build中添加单元测试test,所以我们可以使用
|
||||
|
||||
```
|
||||
meson test
|
||||
```
|
||||
|
||||
或者:
|
||||
|
||||
```
|
||||
ninja test
|
||||
```
|
||||
|
||||
如果指定目录:
|
||||
|
||||
```
|
||||
meson test -C build/
|
||||
|
||||
or
|
||||
|
||||
ninja test -C build/
|
||||
```
|
||||
|
||||
运行日志:
|
||||
|
||||
```
|
||||
➜ gtest_div meson test -C build
|
||||
ninja: Entering directory `/Users/light/work/practice/gtest_div/build'
|
||||
ninja: no work to do.
|
||||
1/1 this is a division test OK 0.01s
|
||||
|
||||
Ok: 1
|
||||
Expected Fail: 0
|
||||
Fail: 0
|
||||
Unexpected Pass: 0
|
||||
Skipped: 0
|
||||
Timeout: 0
|
||||
|
||||
Full log written to /Users/light/work/practice/gtest_div/build/meson-logs/testlog.txt
|
||||
```
|
||||
80
site_extras/cpp-tools-stl-debug-mode.md
Normal file
80
site_extras/cpp-tools-stl-debug-mode.md
Normal file
@@ -0,0 +1,80 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/stl-debug-mode/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ STL Debug 模式
|
||||
|
||||
## 问题
|
||||
|
||||
Project阶段的schema里面的fields发生了变化,fields是一个vector节点,每个成员是`std::shared_ptr<arrow::Field>`,对比前后的vector指针发现`_M_impl`的`_M_start`位置发生了变化,因此需要gdb watch其变化,查看何处改了它。
|
||||
|
||||
## Vector结构
|
||||
|
||||
vecotr代码:
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/stl_vector.h
|
||||
|
||||
```cpp
|
||||
typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type>::pointer
|
||||
pointer;
|
||||
struct _Vector_impl_data
|
||||
{
|
||||
pointer _M_start;
|
||||
pointer _M_finish;
|
||||
pointer _M_end_of_storage;
|
||||
}
|
||||
```
|
||||
|
||||
需要知道几个重要信息:
|
||||
|
||||
- `_M_start`与`_M_finish`等都是pointer类型
|
||||
- pointer类型是原始指针类型
|
||||
|
||||
有了这个信息,我们watch便可以非常方便的观察这个`_M_start`发生了什么变化,注意:是这个指针`_M_start`发生了变化,而不是其值发生了变化。
|
||||
|
||||
## Watch
|
||||
|
||||
首先打印其地址:
|
||||
|
||||
```cpp
|
||||
(gdb) p &((arrow::Schema::Impl *)this->output_schema_->impl_)->fields_._M_impl._M_start
|
||||
$10 = (std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer *) 0xb11dd0
|
||||
```
|
||||
|
||||
我们得到了`pointer* `的地址,然后watch它。
|
||||
|
||||
```cpp
|
||||
(gdb) watch *((std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer *) 0xb11dd0)
|
||||
Hardware watchpoint 2: *((std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer *) 0xb11dd0)
|
||||
```
|
||||
|
||||
随后我们continue,变得了变更点:
|
||||
|
||||
```cpp
|
||||
(gdb) c
|
||||
Continuing.
|
||||
|
||||
|
||||
Thread 1 "postgres" hit Hardware watchpoint 2: *((std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer *) 0xb11dd0)
|
||||
|
||||
Old value = (std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer) 0x979470
|
||||
New value = (std::_Vector_base<std::shared_ptr<arrow::Field>, std::allocator<std::shared_ptr<arrow::Field> > >::pointer) 0x9fe1e0
|
||||
VecSeqNext (node=0x9fdc40) at src/backend/vecexecutor/nodeSeqscan.c:210
|
||||
210 if (table_scan_getnextslot(scandesc, direction, slot))
|
||||
(gdb) bt
|
||||
#0 VecSeqNext (node=0x9fdc40) at src/backend/vecexecutor/nodeSeqscan.c:210
|
||||
#1 0x00007f45994e5c70 in ExecVecScanFetchInternal
|
||||
(node=0x9fdc40, accessMtd=0x7f45994e6335 <VecSeqNext>, recheckMtd=0x7f45994e6430 <VecSeqRecheck>) at src/backend/vecexecutor/execScan.c:146
|
||||
#2 0x00007f45994e58da in ExecVecScanFetch (node=0x9fdc40, accessMtd=0x7f45994e6335 <VecSeqNext>, recheckMtd=0x7f45994e6430 <VecSeqRecheck>)
|
||||
at src/backend/vecexecutor/execScan.c:40
|
||||
#3 0x00007f45994e5d0b in ExecVecScan
|
||||
(node=0x9fdc40, vestate=0x9fdd48, accessMtd=0x7f45994e6335 <VecSeqNext>, recheckMtd=0x7f45994e6430 <VecSeqRecheck>)
|
||||
at src/backend/vecexecutor/execScan.c:200
|
||||
#4 0x00007f45994e6487 in ExecVecSeqScan (pstate=0x9fdc40) at src/backend/vecexecutor/nodeSeqscan.c:246
|
||||
#5 0x00007f45994c40ce in VecExecProcNodeGPDB (node=0x9fdc40) at src/backend/hook/executor.c:102
|
||||
#6 0x00007f45994c41c2 in VecExecProcNodeFirst (node=0x9fdc40) at src/backend/hook/executor.c:153
|
||||
#7 0x00007f45994dc610 in ExecProcNode (node=0x9fdc40) at /home/gpadmin/install/cbdb/include/postgresql/server/executor/executor.h:281
|
||||
#8 0x00007f45994e2065 in get_current_next_batch (node=0x9fdc40) at src/backend/vecexecutor/execMain.c:1851
|
||||
#9 0x00007f4599375c76 in get_arrow_record_batch(GetNextCallback, void*) (fn=0x7f45994e204d <get_current_next_batch>, arg=0x9fdc40)
|
||||
at c_glib/arrow-glib/reader.cpp:216
|
||||
|
||||
|
||||
```
|
||||
60
site_extras/cpp-tools-vscode-cpp-formatting.md
Normal file
60
site_extras/cpp-tools-vscode-cpp-formatting.md
Normal file
@@ -0,0 +1,60 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-tools/vscode-cpp-formatting/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# VS Code 格式化 C++ 代码
|
||||
|
||||
## 《C++那些事》之Step by Step格式化代码风格
|
||||
|
||||
## 0.导语
|
||||
|
||||
本节从0开始讲解如何格式化自己的代码风格,所讲内容实用vscode插件。
|
||||
|
||||
## 1.依赖
|
||||
|
||||
本次使用的是clang-format插件,具体安装比较简单:
|
||||
|
||||
mac系统:
|
||||
|
||||
```cpp
|
||||
brew install clang-format #Mac OS
|
||||
```
|
||||
|
||||
如果是ubuntu:
|
||||
|
||||
```
|
||||
apt install clang-format
|
||||
```
|
||||
|
||||
Windows版本的,可以在这里下载:
|
||||
|
||||
> https://llvm.org/builds/
|
||||
|
||||
安装好之后,进行验证:
|
||||
|
||||
```cpp
|
||||
clang-format --version
|
||||
```
|
||||
|
||||
**如果不想使用vscode的,可以直接clang-format裸命令使用也是可以的!**
|
||||
|
||||
随后在vscode里面下载好以下两个插件:
|
||||
|
||||
- c/c++
|
||||
- clang-format
|
||||
|
||||
这两个在插件市场里面下载即可。
|
||||
|
||||
安装完之后,需要做一些配置,见后文。
|
||||
|
||||
## 2.配置
|
||||
|
||||
vscode设置里面可以搜索Clang_format_style,默认是file,这里可以不用改,当然你也可以设置为其他的,这里我给大家看一下这里的默认值为file,它表示读取当前文件夹或父目录里面的`.clang-format`文件进行格式化。
|
||||
|
||||
所以我们只需要生成这个文件即可,进入代码目录运行:
|
||||
|
||||
```cpp
|
||||
clang-format -style=google -dump-config > .clang-format
|
||||
```
|
||||
|
||||
此时便会生成这个文件,这里采用google风格,你可以对这个文件自行修改。
|
||||
|
||||
对照下图设置vscode里面的clang-format插件格式,最后在文件里面alt+shift+f便可以格式化文件了,为了不必每次都按这个快捷键,当文件保存之后就格式化,大家可以勾选format on save。
|
||||
38
site_extras/how-to-build-cplusplusthings.md
Normal file
38
site_extras/how-to-build-cplusplusthings.md
Normal file
@@ -0,0 +1,38 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/how-to-build-cplusplusthings/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# 编译与运行指南
|
||||
|
||||
## 1.下载
|
||||
|
||||
安装好git,使用下面命令:
|
||||
|
||||
```
|
||||
git clone git@github.com:Light-City/CPlusPlusThings.git
|
||||
```
|
||||
|
||||
## 2.编译环境
|
||||
|
||||
- IDE推荐
|
||||
|
||||
[CLION](https://www.jetbrains.com/clion/)
|
||||
|
||||
- 编译器
|
||||
|
||||
[GCC/G++](https://ftp.gnu.org/gnu/gcc/)
|
||||
|
||||
|
||||
## 3.编译本项目
|
||||
|
||||
方式一: vscode + bazel
|
||||
|
||||
[第一期:Step By Step上手编译本项目](https://www.bilibili.com/video/BV1Rv4y1H7LB/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
方式二: 免开发环境docker
|
||||
|
||||
[第二期:免开发环境docker](https://www.bilibili.com/video/BV1oz4y1a7Pu/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
```
|
||||
docker pull xingfranics/cplusplusthings:latest
|
||||
```
|
||||
|
||||
方式三: gcc/g++
|
||||
76
site_extras/modern-cpp-cpp11-cpp-std-move.md
Normal file
76
site_extras/modern-cpp-cpp11-cpp-std-move.md
Normal file
@@ -0,0 +1,76 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp11/cpp-std-move/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ std::move 原理与用法
|
||||
|
||||
`std::move` 是一个非常重要的函数,它提供了一种方式,可以将一个左值对象标记为一个特殊类型的右值对象,即 xvalue。这种转变是为了允许执行移动语义,而不是执行常规的拷贝语义。
|
||||
|
||||
- 为什么要使用 std::move
|
||||
- 实际应用场景
|
||||
|
||||
## 1.为什么要使用 std::move
|
||||
|
||||
|
||||
|
||||
通常情况下,只有右值对象才能进行移动操作,因为移动构造函数使用右值引用作为参数,而右值引用只能绑定到右值。因此,如果你想从一个由左值表达式表示的对象中执行移动操作,你需要使用 `std::move` 来将其转换为一个 xvalue(特殊的右值)。
|
||||
|
||||
使用 `std::move` 时需要谨慎,因为移动操作会将对象置于一个通常只允许销毁的状态。因此,最好仅对对象的最后一次使用进行移动操作。
|
||||
|
||||
`std::move` 并不实际执行移动,需要明确的是,`std::move` 并不会实际执行对象的移动操作。它只是将给定的左值对象转换为右值引用。下面是 `std::move` 的一个可能实现:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
typename remove_reference<T>::type&& move(T&& t)
|
||||
{
|
||||
return static_cast<typename remove_reference<T>::type&&>(t);
|
||||
}
|
||||
```
|
||||
|
||||
## 2.实际使用场景
|
||||
|
||||
### 2.1 移动构造而非拷贝构造
|
||||
|
||||
在函数 `f1` 中,参数 `a` 是一个右值引用的左值,而不是右值本身,因为它有一个名称。因此,为了强制执行 `Foo` 的移动构造,我们必须将其转换为一个右值,而 `std::move` 恰好可以完美地做到这一点。
|
||||
|
||||
```cpp
|
||||
struct Foo {
|
||||
...
|
||||
Foo(const Foo&) {}
|
||||
Foo(Foo&&) {}
|
||||
};
|
||||
|
||||
void f1(Foo&& a) {
|
||||
Foo b(a); // 调用拷贝构造函数,而非移动构造函数
|
||||
}
|
||||
|
||||
void f2(Foo&& a) {
|
||||
Foo b(std::move(a)); // right
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### 2.2 所有权管理
|
||||
|
||||
假设有如下代码:
|
||||
|
||||
```
|
||||
Foo* p = new Foo();
|
||||
data.push_back(p);
|
||||
```
|
||||
|
||||
上述代码可以正常工作,但你无法确定指针的所有权归属。谁来删除指针?或者指针应该在何时被删除?它会在容器被销毁时被删除吗?
|
||||
|
||||
在 C++11 中,`std::unique_ptr<Foo> p(new Foo());` 这条语句会产生编译错误。原因在于唯一所有权规则被应用。
|
||||
|
||||
但是,你可以使用 `std::move` 来转移指针的所有权:
|
||||
|
||||
```
|
||||
data.push_back(std::move(p));
|
||||
```
|
||||
|
||||
现在,指针的所有权被转移到了容器中,在容器生命周期结束时将被删除。虽然对象 `p` 仍然存在,但任何试图解引用它的尝试将生成空指针异常。
|
||||
|
||||
事实上,在移动操作之后,`p` 拥有的内部指针已经被设置为 `nullptr`。
|
||||
|
||||
综上所述,`std::move` 的作用在于提供了一种手段,能够安全地实现对象的移动语义,转变其左值属性为右值,使其可以被移动构造函数或移动赋值操作符所调用。正确地使用 `std::move` 可以提高性能并确保正确的所有权转移。
|
||||
|
||||
那么下一个问题,什么时候不需要使用std::move呢?
|
||||
58
site_extras/modern-cpp-cpp11-std-bind-vs-lambda.md
Normal file
58
site_extras/modern-cpp-cpp11-std-bind-vs-lambda.md
Normal file
@@ -0,0 +1,58 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp11/std-bind-vs-lambda/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ std::bind 与 lambda 对比
|
||||
|
||||
https://quick-bench.com/q/CEnR_XUuIwnZxaP4KJNSlpYG38c
|
||||
|
||||
```
|
||||
#include <functional>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
|
||||
|
||||
struct Calculator {
|
||||
int count{1};
|
||||
int total{0};
|
||||
|
||||
auto calculate() -> void {
|
||||
using std::iota, std::vector;
|
||||
|
||||
// Random math
|
||||
vector<int> u(8), v(Calculator::count * u.size());
|
||||
|
||||
iota(v.begin(), v.end(), *u.begin());
|
||||
|
||||
int sum{*v.begin() + *u.begin()};
|
||||
|
||||
for (size_t pos{0}; pos < v.size(); ++pos) {
|
||||
sum += u[pos % u.size()] * v[pos];
|
||||
}
|
||||
|
||||
Calculator::total += sum;
|
||||
++Calculator::count;
|
||||
}
|
||||
};
|
||||
|
||||
// auto f(std::function<void(int)> g) -> void { g(rand()); }
|
||||
|
||||
template<typename FN> auto f(FN g) -> void { g(rand()); }
|
||||
|
||||
|
||||
static auto BM_bind(benchmark::State& state) -> void {
|
||||
Calculator calculator;
|
||||
for (auto _ : state) {
|
||||
f(std::bind(&Calculator::calculate, &calculator));
|
||||
}
|
||||
}
|
||||
|
||||
static auto BM_lambda(benchmark::State& state) -> void {
|
||||
Calculator calculator;
|
||||
for (auto _ : state) {
|
||||
f([&calculator]([[maybe_unused]] int x) { calculator.calculate(); });
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(BM_bind);
|
||||
BENCHMARK(BM_lambda);
|
||||
```
|
||||
146
site_extras/modern-cpp-cpp11-variadic-templates-cpp.md
Normal file
146
site_extras/modern-cpp-cpp11-variadic-templates-cpp.md
Normal file
@@ -0,0 +1,146 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp11/variadic-templates-cpp/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 可变参数模板
|
||||
|
||||
## 《C++那些事》之可变参数模版
|
||||
|
||||
最近在看Arrow的源代码发现了一个比较有意思的设计,在一个plan中可以添加多个节点,例如:proj、agg等等。
|
||||
|
||||
今天来讲讲这一块的设计与实现。
|
||||
|
||||
## 1.添加节点
|
||||
|
||||
对于一个plan通常需要添加一堆节点,这里便是调用EmplaceNode来实现的。
|
||||
|
||||
```cpp
|
||||
return plan->EmplaceNode<ScalarAggregateNode>(
|
||||
plan, std::move(inputs), schema(std::move(fields)), std::move(target_field_ids),
|
||||
std::move(aggregates), std::move(kernels), std::move(states),
|
||||
std::move(owned_options));
|
||||
```
|
||||
|
||||
同理,如果添加一个proj节点就是:
|
||||
|
||||
```cpp
|
||||
return plan->EmplaceNode<ProjectNode>(plan, std::move(inputs),
|
||||
schema(std::move(fields)), std::move(exprs),
|
||||
project_options.async_mode);
|
||||
```
|
||||
|
||||
那么究竟是什么魅力让代码写的如此丝滑?
|
||||
|
||||
这里把Plan简单写一下:
|
||||
|
||||
```cpp
|
||||
class ARROW_EXPORT ExecPlan
|
||||
{
|
||||
public:
|
||||
template <typename Node, typename... Args>
|
||||
Node* EmplaceNode(Args&&... args) {
|
||||
std::unique_ptr<Node> node{new Node{std::forward<Args>(args)...}};
|
||||
auto out = node.get();
|
||||
AddNode(std::move(node));
|
||||
return out;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
看上这个语法非常的复杂,没错,它是11之后的可变参数模版,这里解释一下这段代码的含义,就是将参数包丢给对应的Node构造函数。这个例子可能看起来比较复杂,接下来我们进入Demo环节。
|
||||
|
||||
### 2.Demo
|
||||
|
||||
接下来我们创建了一个图,图中有两个不同的节点,分别是节点 A与 节点B,为了简单器件这里使用一个函数模版EmplaceNode。
|
||||
|
||||
```cpp
|
||||
NodeA* nodeA = EmplaceNode<NodeA>("Node A", 10, 3.14);
|
||||
NodeB* nodeB = EmplaceNode<NodeB>(1, "Node B");
|
||||
```
|
||||
|
||||
完整代码如下:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
class NodeA {
|
||||
public:
|
||||
NodeA(const std::string& name, int value, double weight)
|
||||
: name_(name), value_(value), weight_(weight) {}
|
||||
|
||||
const std::string& GetName() const {
|
||||
return name_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
int value_;
|
||||
double weight_;
|
||||
};
|
||||
|
||||
class NodeB {
|
||||
public:
|
||||
NodeB(int id, const std::string& desc)
|
||||
: id_(id), desc_(desc) {}
|
||||
|
||||
int GetID() const {
|
||||
return id_;
|
||||
}
|
||||
|
||||
private:
|
||||
int id_;
|
||||
std::string desc_;
|
||||
};
|
||||
template<typename Node, typename... Args>
|
||||
Node* EmplaceNode(Args&&... args) {
|
||||
std::unique_ptr<Node> node{new Node{std::forward<Args>(args)...}};
|
||||
auto out = node.get();
|
||||
// AddNode(std::move(node));
|
||||
return out;
|
||||
}
|
||||
|
||||
int main() {
|
||||
NodeA* nodeA = EmplaceNode<NodeA>("Node A", 10, 3.14);
|
||||
NodeB* nodeB = EmplaceNode<NodeB>(1, "Node B");
|
||||
std::cout << "Node A name: " << nodeA->GetName() << std::endl;
|
||||
std::cout << "Node B ID: " << nodeB->GetID() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## 3.拓展-实现一个print函数可以打印任意类型数据
|
||||
|
||||
简单实现版本:
|
||||
|
||||
使用可变模版参数+递归方式实现即可。
|
||||
|
||||
每次拆分成一个+一堆,直到只剩下一个,所以有一个处理一个的函数与处理一个+一堆的函数,分别对应第一个print_impl与第二个print_impl。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
template <typename T>
|
||||
void print_impl(T&& t) {
|
||||
std::cout << t;
|
||||
}
|
||||
|
||||
template <typename T, typename... Args>
|
||||
void print_impl(T&& t, Args&&... args) {
|
||||
std::cout << t;
|
||||
print_impl(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void print(Args&&... args) {
|
||||
print_impl(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
int main() {
|
||||
int x = 1;
|
||||
const char* str = "Hello, world!";
|
||||
print("The value of x is ", x, ", and the string is ", str, ".\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
78
site_extras/modern-cpp-cpp17-cpp-nodiscard.md
Normal file
78
site_extras/modern-cpp-cpp17-cpp-nodiscard.md
Normal file
@@ -0,0 +1,78 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/cpp-nodiscard/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 [[nodiscard]] 属性
|
||||
|
||||
自C++17引入[[nodiscard]]属性以来,我们在编写API时有了一种更强大的工具,用于标记那些在调用时不应该被忽略的函数返回值。在本文中,我们将深入探讨[[nodiscard]]的用法,并注意一些潜在的陷阱。
|
||||
|
||||
## 什么是[[nodiscard]]?
|
||||
|
||||
[[nodiscard]]是一种函数属性,它告诉编译器函数的返回值不应该被忽略。这在那些依赖于返回值的函数中尤为有用,例如谓词函数或工厂函数。
|
||||
|
||||
## 如何使用[[nodiscard]]?
|
||||
|
||||
在类、构造函数以及枚举上使用[[nodiscard]]都是可能的。下面是一些示例:
|
||||
|
||||
```cpp
|
||||
class [[nodiscard]] A {};
|
||||
|
||||
class B {
|
||||
public:
|
||||
[[nodiscard]] B() = default;
|
||||
};
|
||||
|
||||
enum class [[nodiscard]] State {
|
||||
Default,
|
||||
Foo,
|
||||
Bar
|
||||
};
|
||||
```
|
||||
|
||||
在上述例子中,编译器将在返回值被忽略时发出警告,有助于我们及早发现潜在的bug。
|
||||
|
||||
## 警惕:[[nodiscard]]的陷阱
|
||||
|
||||
尽管[[nodiscard]]可以有效地防止返回值被无意中忽略,但我们需要注意一些潜在的陷阱。一个常见的陷阱是使用[[nodiscard]]的函数返回一个类似于作用域守卫的对象,以在作用域结束时执行清理操作(比如提交事务)。
|
||||
|
||||
```cpp
|
||||
[[nodiscard]] ScopeGuard createScopeGuard() {
|
||||
// Implementation of a scope guard
|
||||
}
|
||||
|
||||
// 在这里,用户可以选择忽略返回值,导致作用域立即销毁,从而失去清理效果
|
||||
std::ignore = createScopeGuard();
|
||||
```
|
||||
|
||||
尽管[[nodiscard]]表明函数返回值不应该被忽略,但用户仍然可以通过`std::ignore`等手段明确地忽略返回值,从而绕过清理操作。
|
||||
|
||||
## 完整示例
|
||||
|
||||
```cpp
|
||||
#include <tuple> // std::ignore
|
||||
|
||||
class [[nodiscard]] A {};
|
||||
class B {
|
||||
public:
|
||||
[[nodiscard]] bool isOk() const { return true; }
|
||||
};
|
||||
|
||||
// no need for nodiscard, A is nodiscard
|
||||
A foo() {
|
||||
return A();
|
||||
}
|
||||
|
||||
// B is not nodiscard, mark it explicitly
|
||||
[[nodiscard]] B bar() {
|
||||
return B();
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
foo(); // warning: ignoring temporary created by a constructor declared with 'nodiscard' attribute
|
||||
bar(); // warning
|
||||
|
||||
std::ignore = foo(); // ok
|
||||
auto b = bar(); // ok
|
||||
b.isOk(); // warning
|
||||
if (b.isOk()) {} // ok
|
||||
}
|
||||
```
|
||||
106
site_extras/modern-cpp-cpp17-cpp-string-view.md
Normal file
106
site_extras/modern-cpp-cpp17-cpp-string-view.md
Normal file
@@ -0,0 +1,106 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/cpp-string-view/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 std::string_view
|
||||
|
||||
## 0.问题
|
||||
|
||||
string_view为c++17之后出现,其实就是leveldb中的slice,其目的在于解决内存拷贝、高效的substr。
|
||||
|
||||
但是,也引入了指针与引用的问题,由于string_view不拥有指向内容的所有权,对比于Rust,仅仅是借用,如果拥有内容的对象提前释放,便会出现悬挂引用问题。像Rust在编译时会分析变量的生命周期,保证借用的资源在使用时不会释放。然而C++没有检查,需要人工保证。
|
||||
|
||||
### 1.内部实现
|
||||
|
||||
string_view是一个basic_string_view类型,可以看到_Traits采用默认的`char_traits`,这个很重要,后面的一些函数都采用`char_traits`的一些成员函数执行核心操作。
|
||||
|
||||
```cpp
|
||||
template<class _CharT, class _Traits = char_traits<_CharT> >
|
||||
class _LIBCPP_TEMPLATE_VIS basic_string_view;
|
||||
|
||||
typedef basic_string_view<char> string_view;
|
||||
```
|
||||
|
||||
basic_string_view内部成员:
|
||||
|
||||
```cpp
|
||||
private:
|
||||
const value_type* __data;
|
||||
size_type __size;
|
||||
```
|
||||
|
||||
构造兼容 string与`const char*`
|
||||
|
||||
```cpp
|
||||
constexpr basic_string_view() noexcept;
|
||||
constexpr basic_string_view(const basic_string_view&) noexcept = default;
|
||||
basic_string_view& operator=(const basic_string_view&) noexcept = default;
|
||||
template<class Allocator>
|
||||
constexpr basic_string_view(const charT* str);
|
||||
constexpr basic_string_view(const charT* str, size_type len);
|
||||
```
|
||||
|
||||
迭代器支持:
|
||||
|
||||
```cpp
|
||||
constexpr const_iterator begin() const noexcept;
|
||||
constexpr const_iterator end() const noexcept;
|
||||
constexpr const_iterator cbegin() const noexcept;
|
||||
constexpr const_iterator cend() const noexcept;
|
||||
const_reverse_iterator rbegin() const noexcept;
|
||||
const_reverse_iterator rend() const noexcept;
|
||||
const_reverse_iterator crbegin() const noexcept;
|
||||
const_reverse_iterator crend() const noexcept;
|
||||
```
|
||||
|
||||
其他核心函数:
|
||||
|
||||
- substr
|
||||
- remove_prefix
|
||||
- compare
|
||||
- find
|
||||
- ...
|
||||
|
||||
从c++20开始支持starts_with、ends_with、contains,这三个在leveldb的slice中一开始就支持了。
|
||||
|
||||
`char*`的string_view字面量:
|
||||
|
||||
```cpp
|
||||
constexpr basic_string_view<char> operator "" sv( const char *str, size_t len ) noexcept;
|
||||
constexpr basic_string_view<wchar_t> operator "" sv( const wchar_t *str, size_t len ) noexcept;
|
||||
constexpr basic_string_view<char16_t> operator "" sv( const char16_t *str, size_t len ) noexcept;
|
||||
constexpr basic_string_view<char32_t> operator "" sv( const char32_t *str, size_t len ) noexcept;
|
||||
```
|
||||
|
||||
## 2.使用陷阱
|
||||
|
||||
### 2.1 `\0`
|
||||
|
||||
string_view不关心`\0`,会关心实际的字符个数。
|
||||
|
||||
```cpp
|
||||
std::string_view s = "abc\0\0def"sv;
|
||||
std::cout << "s: " << s.size() << " \"" << s << "\"\n";
|
||||
```
|
||||
|
||||
输出:s: 8 "abcdef"
|
||||
|
||||
```cpp
|
||||
std::string_view str{"hello", 1};
|
||||
std::cout << str.data() << std::endl; // 输出 hello,而不是h
|
||||
```
|
||||
|
||||
这里预期输出hello,但是却输出了h。
|
||||
|
||||
### 2.2 生命周期
|
||||
|
||||
```cpp
|
||||
string_view foo() {
|
||||
std::string s{"hello world"};
|
||||
return string_view{s};
|
||||
}
|
||||
```
|
||||
|
||||
在该示例中,s出了作用域,string_view变成了悬空引用。
|
||||
|
||||
|
||||
!!! warning "生命周期"
|
||||
`std::string_view` 不拥有底层字符存储,务必保证被引用对象的生命周期覆盖全部使用期。
|
||||
309
site_extras/modern-cpp-cpp17-cpp17-pmr.md
Normal file
309
site_extras/modern-cpp-cpp17-cpp17-pmr.md
Normal file
@@ -0,0 +1,309 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/cpp17-pmr/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 PMR 内存资源
|
||||
|
||||
[TOC]
|
||||
|
||||
## 1.引入
|
||||
|
||||
在C++17之前,标准库提供了`std::allocator`,而在C++17中,这一功能得到了加强,引入了`polymorphic_allocator`。
|
||||
|
||||
在C++17之前,如果我们想要使用`std::allocator`来自定义内存池,我们不能使用传统的虚拟多态方式,因为`std::allocator`并没有提供虚拟函数。因此,通过继承显然不是一个好的选择,但是我们可以将其作为类成员使用,如下所示:
|
||||
|
||||
```cpp
|
||||
template <typename Allocator = std::allocator<uint8_t>>
|
||||
class MemoryPool {
|
||||
public:
|
||||
explicit STLMemoryPool(const Allocator& alloc) : alloc_(alloc) {}
|
||||
|
||||
Status Allocate(int64_t size, uint8_t** out) {
|
||||
try {
|
||||
*out = alloc_.allocate(size);
|
||||
} catch (std::bad_alloc& e) {
|
||||
return Status::OutOfMemory(e.what());
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
void Free(uint8_t* buffer, int64_t size) {
|
||||
alloc_.deallocate(buffer, size);
|
||||
}
|
||||
|
||||
private:
|
||||
Allocator alloc_;
|
||||
};
|
||||
```
|
||||
|
||||
在C++17之前如果我们想在内存分配/释放时做一些print操作,或者一些自定义操作,可以使用两种办法:
|
||||
|
||||
- 自定义全局的new/delete
|
||||
|
||||
```cpp
|
||||
void* operator new(std::size_t size) {
|
||||
void* ptr = malloc(size);
|
||||
std::cout << "Allocated: " << size << " bytes at address " << ptr << std::endl;
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void operator delete(void* ptr, std::size_t n) noexcept {
|
||||
std::cout << "Deallocated: " << n << " bytes at address " << ptr << std::endl;
|
||||
free(ptr);
|
||||
}
|
||||
```
|
||||
|
||||
- 自定义allocator
|
||||
|
||||
```cpp
|
||||
class allocator {
|
||||
public:
|
||||
using value_type = T;
|
||||
value_type* allocate(std::size_t n) {
|
||||
value_type* p = static_cast<value_type*>(::operator new(n * sizeof(value_type)));
|
||||
std::cout << "Allocated: " << n * sizeof(value_type) << " bytes at address "
|
||||
<< static_cast<void*>(p) << std::endl;
|
||||
return p;
|
||||
}
|
||||
|
||||
void deallocate(value_type* p, std::size_t n) noexcept {
|
||||
std::cout << "Deallocated: " << n * sizeof(value_type) << " bytes at address "
|
||||
<< static_cast<void*>(p) << std::endl;
|
||||
::operator delete(p);
|
||||
}
|
||||
};
|
||||
|
||||
std::vector<int, allocator<int>> vec;
|
||||
```
|
||||
|
||||
那么,除此之外,还有哪些办法呢?
|
||||
|
||||
C++17之后,我们可以通过使用多态内存管理工具,polymorphic memory resources(pmr),使用方式:
|
||||
|
||||
```cpp
|
||||
#include <memory_resources>
|
||||
|
||||
pmr::monotonic_buffer_resource res(10);
|
||||
pmr::vector<vector<int>> vec1(&res);
|
||||
```
|
||||
|
||||
对于上面这个问题,我们可以通过继承memory_resource,有关下面代码的解释见下方memory_resource。
|
||||
|
||||
```cpp
|
||||
class TrackAllocator : public std::pmr::memory_resource {
|
||||
void* do_allocate(std::size_t bytes, std::size_t alignment) override {
|
||||
void* p = std::pmr::new_delete_resource()->allocate(bytes, alignment);
|
||||
std::cout << "do_allocate: " << bytes << " bytes at " << p
|
||||
<< " alignment: " << alignment << std::endl;
|
||||
return p;
|
||||
}
|
||||
|
||||
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override {
|
||||
std::cout << "do_deallocate: " << bytes << " bytes at "
|
||||
<< " alignment: " << alignment << std::endl;
|
||||
return std::pmr::new_delete_resource()->deallocate(p, bytes, alignment);
|
||||
}
|
||||
|
||||
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override {
|
||||
return std::pmr::new_delete_resource()->is_equal(other);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
至此,我们便做到了上面的效果。
|
||||
|
||||
## 2.memory_resource
|
||||
|
||||
STL中std::par::memory_resource类的实现比较简单,以下为一个伪代码实现:
|
||||
|
||||
```cpp
|
||||
class memory_resource {
|
||||
static const size_t __max_align = alignof(max_align_t);
|
||||
|
||||
public:
|
||||
virtual ~memory_resource();
|
||||
|
||||
void* allocate(size_t __bytes, size_t __align = __max_align) {
|
||||
return do_allocate(__bytes, __align);
|
||||
}
|
||||
|
||||
void deallocate(void* __p, size_t __bytes, size_t __align = __max_align) {
|
||||
do_deallocate(__p, __bytes, __align);
|
||||
}
|
||||
|
||||
bool is_equal(const memory_resource& __other) const noexcept {
|
||||
return do_is_equal(__other);
|
||||
}
|
||||
|
||||
private:
|
||||
virtual void* do_allocate(size_t, size_t) = 0;
|
||||
virtual void do_deallocate(void*, size_t, size_t) = 0;
|
||||
virtual bool do_is_equal(memory_resource const&) const noexcept = 0;
|
||||
};
|
||||
```
|
||||
|
||||
与默认的std::allocator不同,memory_resource提供了多态的能力,允许用户通过继承的方式,重写以下三个接口:
|
||||
|
||||
- do_allocate
|
||||
- 用于分配指定大小和对齐要求的内存。
|
||||
- do_deallocate
|
||||
- 释放之前通过 `do_allocate` 分配的内存。
|
||||
- do_is_equal
|
||||
- 检查当前内存资源对象是否与另一个内存资源对象相等。
|
||||
|
||||
于是,我们上方的TrackAllocator通过重写上面三个函数接口即可。
|
||||
|
||||
细心的朋友发现,除了这几个接口,memory_resource也提供了对外的三个接口。除此之外,提供了全局的接口:
|
||||
|
||||
```cpp
|
||||
memory_resource* new_delete_resource() noexcept;
|
||||
memory_resource* null_memory_resource() noexcept;
|
||||
memory_resource* get_default_resource() noexcept;
|
||||
memory_resource* set_default_resource(memory_resource* __r) noexcept;
|
||||
```
|
||||
|
||||
- new_delete_resource
|
||||
|
||||
返回一个`memory_resource`指针,该指针使用`new`和`delete`运算符来分配和释放内存。这个资源是使用全局的`new`和`delete`运算符实现的,因此它是默认的内存资源管理器。这个memory_resource子类是`__resource_adaptor_imp`,它会负责重写上面三个接口。
|
||||
|
||||
- null_memory_resource
|
||||
|
||||
返回一个`memory_resource`指针,该指针表示一个不执行任何操作的空内存资源。当你想要在不进行实际内存分配的情况下测试或占位时,可以使用这个资源。STL源码当中的实现中定义了一个
|
||||
|
||||
```cpp
|
||||
inline memory_resource*
|
||||
null_memory_resource() noexcept {
|
||||
class type final : public memory_resource {};
|
||||
}
|
||||
```
|
||||
|
||||
type作为子类重写了上面三个接口,do_allocate接口会跑出分配错误的异常,因为语义就是不允许分配了。
|
||||
|
||||
```
|
||||
do_allocate(size_t, size_t) override
|
||||
{ std::__throw_bad_alloc(); }
|
||||
```
|
||||
|
||||
所以当我们使用null_memory_resource,需要try catch,例如:string字符小于16是在stack上分配,此时不会用到我们这里的memory_resource,所以正常运行,当长度大于等于16,那么就会跑出std::bad_alloc异常。
|
||||
|
||||
```cpp
|
||||
std::pmr::memory_resource* default_resource = std::pmr::null_memory_resource();
|
||||
|
||||
std::pmr::set_default_resource(default_resource);
|
||||
|
||||
try {
|
||||
std::pmr::vector<int> data{1};
|
||||
} catch (std::bad_alloc e) {
|
||||
std::cerr << "bad_alloc is thrown vector" << std::endl;
|
||||
}
|
||||
|
||||
std::pmr::string str1{"hello world hel"};
|
||||
std::cerr << str1 << " length:" << str1.size() << std::endl;
|
||||
|
||||
try {
|
||||
std::pmr::string str1{"hello world hel0"};
|
||||
} catch (std::bad_alloc e) {
|
||||
std::cerr << "bad_alloc is thrown string" << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
- get_default_resource
|
||||
|
||||
返回当前默认的全局内存资源管理器。默认情况下,它是一个与`new_delete_resource()`返回的相同资源,但通过`set_default_resource`函数可以更改默认资源。
|
||||
|
||||
- set_default_resource
|
||||
|
||||
设置内存资源管理器,参数可以为空(返回默认资源),否则设置为传递的资源,并返回之前的默认资源。
|
||||
|
||||
## 3.内存复用
|
||||
|
||||
std::pmr::monotonic_buffer_resource是一个缓存区,在内存复用方面具有重要的优势。monotonic_buffer_resource继承memory_resource,重写上面三个接口,内部会持有上游的memory_resource,如果当前内存不足,便会从上游去取。这有助于降低内存碎片,提高内存利用率。
|
||||
|
||||
下面列出一些有关std::pmr::monotonic的使用方法。
|
||||
|
||||
**用法1 - 使用固定缓冲区创建 `monotonic_buffer_resource`:**
|
||||
|
||||
```cpp
|
||||
char buf1[30] = {};
|
||||
std::fill_n(std::begin(buf1), std::size(buf1) - 1, '_');
|
||||
std::pmr::monotonic_buffer_resource pool1{std::data(buf1), std::size(buf1)};
|
||||
std::pmr::vector<int> myVec1{&pool1};
|
||||
```
|
||||
|
||||
**用法2 - 利用上游资源创建 `monotonic_buffer_resource`:**
|
||||
|
||||
```cpp
|
||||
std::pmr::memory_resource* upstreamResource2 = std::pmr::get_default_resource();
|
||||
std::pmr::monotonic_buffer_resource pool2(upstreamResource2);
|
||||
{
|
||||
std::pmr::vector<double> numbers(&pool2);
|
||||
for (double d = 0.1; d < 1.0; d += 0.1) {
|
||||
numbers.push_back(d);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**用法3 - 继承std::pmr::monotonic_buffer_resource:**
|
||||
|
||||
```cpp
|
||||
class MyMonotonicBufferResource : public std::pmr::monotonic_buffer_resource {
|
||||
public:
|
||||
using std::pmr::monotonic_buffer_resource::monotonic_buffer_resource; // Inherit constructors
|
||||
|
||||
// Public function to access do_allocate
|
||||
void* allocate(std::size_t bytes, std::size_t alignment) {
|
||||
return do_allocate(bytes, alignment);
|
||||
}
|
||||
|
||||
// Public function to access do_deallocate
|
||||
void deallocate(void* p, std::size_t bytes, std::size_t alignment) {
|
||||
do_deallocate(p, bytes, alignment);
|
||||
}
|
||||
};
|
||||
|
||||
MyMonotonicBufferResource pool3;
|
||||
// Allocate memory
|
||||
void* mem = pool3.allocate(100, alignof(int));
|
||||
|
||||
// Use the allocated memory (this is just an example)
|
||||
std::pmr::vector<int> numbers({1, 2, 3}, &pool3);
|
||||
|
||||
// Deallocate memory
|
||||
pool3.deallocate(mem, 100, alignof(int));
|
||||
|
||||
std::cout << "Usage 3 - Inherit: \n\n";
|
||||
```
|
||||
|
||||
## 4.pool resource
|
||||
|
||||
synchronized_pool_resource这是一个线程安全的内存池资源类。它的设计目的是在多线程环境中安全地进行内存分配和释放。当多个线程并发地尝试进行内存分配或释放时,`synchronized_pool_resource` 使用同步机制确保线程安全性。这通常会带来一些性能开销,因为需要加锁来保护共享的内存池。
|
||||
|
||||
与之对应的是unsynchronized_pool_resource,需要用户自己保证线程安全。
|
||||
|
||||
synchronized_pool_resource源码实现其实就是mutex + unsynchronized_pool_resource。
|
||||
|
||||
```cpp
|
||||
class synchronized_pool_resource : public memory_resource {
|
||||
|
||||
public:
|
||||
// some interface
|
||||
private:
|
||||
mutex __mut_;
|
||||
unsynchronized_pool_resource __unsync_;
|
||||
};
|
||||
```
|
||||
|
||||
pool_options可以用来配置这些内存池。
|
||||
|
||||
```cpp
|
||||
struct pool_options {
|
||||
size_t max_blocks_per_chunk = 0;
|
||||
size_t largest_required_pool_block = 0;
|
||||
};
|
||||
```
|
||||
|
||||
- max_blocks_per_chunk
|
||||
|
||||
表示每个块中最多可以包含的块数量。用于限制内存池从上游内存资源一次性获取的内存量。如果设置为 0,内核会通过munge_options函数去修改pool_options。
|
||||
|
||||
- largest_required_pool_block
|
||||
|
||||
表示内存池能够处理的最大块大小。
|
||||
330
site_extras/modern-cpp-cpp17-cpp17-top-17-features.md
Normal file
330
site_extras/modern-cpp-cpp17-cpp17-top-17-features.md
Normal file
@@ -0,0 +1,330 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/cpp17-top-17-features/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 十七项高级特性
|
||||
|
||||
### 全面盘点17个C++17的高级特性
|
||||
|
||||
|
||||
|
||||
C++17是目前比较常用的版本之一,今天花时间来梳理一下17个重要特性,所有的特性也不止这么点。
|
||||
|
||||
[TOC]
|
||||
|
||||
### 1. 并行算法
|
||||
|
||||
C++17引入了许多并行版本的标准库中的算法。这些算法可以并行执行,因此在多核系统上可能会带来显著的性能提升。
|
||||
|
||||
之前写过一篇全面介绍这个特性的文章,可以看这篇:
|
||||
|
||||
例子:
|
||||
|
||||
```cpp
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <execution>
|
||||
int main() {
|
||||
std::vector<int> v = {1, 2, 3, 4, 5};
|
||||
std::sort(std::execution::par, v.begin(), v.end());
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,`std::sort`是并行执行的,以并行方式对向量`v`的元素进行排序。
|
||||
|
||||
### 2. If Initializers
|
||||
|
||||
C++17中的If初始化器是一项特性,它允许在if语句中直接初始化变量。这种初始化方式在一定程度上可以提高代码的可读性和简洁性。
|
||||
|
||||
在传统的C++中,我们通常会这样初始化变量:
|
||||
|
||||
```cpp
|
||||
int x;
|
||||
if (condition) {
|
||||
x = 42;
|
||||
} else {
|
||||
x = 24;
|
||||
}
|
||||
```
|
||||
|
||||
而在C++17中,可以使用if初始化器来简化这个过程,使代码更加紧凑:
|
||||
|
||||
```cpp
|
||||
if (bool condition = /* some condition */) {
|
||||
int x = 42;
|
||||
} else {
|
||||
int x = 24;
|
||||
}
|
||||
```
|
||||
|
||||
在这个例子中,我们将变量`x`的初始化直接放在if语句中。变量`condition`在if语句中被定义和初始化,然后在if语句块中可用。这种方式更加直观和简洁,尤其是在简单的条件初始化时。
|
||||
|
||||
### 3. 类模板参数推导(CTAD)
|
||||
|
||||
CTAD 让编译器从函数参数中自动推导出模板参数。这使得在不必显式指定模板参数的情况下更容易地使用模板。
|
||||
|
||||
往期对这个特性的全面阐述文章:
|
||||
|
||||
例子:
|
||||
|
||||
```
|
||||
template <typename T>
|
||||
void foo(T t) {
|
||||
// ...
|
||||
}
|
||||
|
||||
int main() {
|
||||
foo(42); // 编译器推导出T的类型为int
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,当调用`foo(42)`时,编译器推导出`T`的类型是`int`.
|
||||
|
||||
### 4. template `<auto>`
|
||||
|
||||
模板关键词被引入为非类型模板参数的占位符。它允许在模板中表示任何类型的值。
|
||||
|
||||
例子:
|
||||
|
||||
```
|
||||
template<auto value>
|
||||
struct constant {
|
||||
static constexpr auto get_value() { return value; }
|
||||
};
|
||||
|
||||
// 用法
|
||||
static_assert(constant<42>::get_value() == 42);
|
||||
```
|
||||
|
||||
### 5. std::optional 和 std::variant
|
||||
|
||||
`std::optional` 和 `std::variant` 是C++17中引入的两个新类型。`std::optional` 表示一个可能存在也可能不存在的值,`std::variant` 代表一个类型安全的联合,可以保存不同类型的值。
|
||||
|
||||
例子:
|
||||
|
||||
```
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
|
||||
int main() {
|
||||
std::optional<int> opt = 42;
|
||||
std::variant<int, double> var = 3.14;
|
||||
}
|
||||
```
|
||||
|
||||
在这个例子中,`opt`是包含值42的可选整数,`var`是包含值3.14的变体。
|
||||
|
||||
### 6. 折叠表达式
|
||||
|
||||
在C++17中,折叠表达式提供了一种简洁的方式,用于对参数包执行二元操作。它们允许在不需要显式递归或迭代的情况下执行诸如求和、乘法或连接参数包中元素的操作。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
template<typename T>
|
||||
T sum(T t) {
|
||||
return t;
|
||||
}
|
||||
|
||||
// 使用折叠表达式的递归情况
|
||||
template<typename T, typename... Args>
|
||||
T sum(T first, Args... args) {
|
||||
return first + sum(args...);
|
||||
}
|
||||
|
||||
int main() {
|
||||
int total = sum(1, 2, 3, 4, 5);
|
||||
std::cout << "总和: " << total << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
递归`sum`函数中的折叠表达式`(first + ... + args)`对参数包中的每个元素应用了加法操作。
|
||||
|
||||
### 7. 结构化绑定
|
||||
|
||||
结构化绑定允许你将对象分解成其构成元素,类似于你可能会用到的元组拆包。
|
||||
|
||||
往期文章:
|
||||
|
||||
例子:
|
||||
|
||||
```
|
||||
#include <tuple>
|
||||
#include <string>
|
||||
int main() {
|
||||
std::tuple<int, std::string, double> t(42, "hello", 3.14);
|
||||
auto [i, s, d] = t; // i = 42, s = "hello", d = 3.14
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,结构化绑定`[i, s, d]`将元组`t`分解成其构成元素。
|
||||
|
||||
### 8.模板模板参数
|
||||
|
||||
例如:在C++17中,语法 `template<template<class...>typename bob> struct foo {}` 声明了一个名为 `foo` 的模板,它接受一个名为 `bob` 的模板模板参数。模板模板参数 `bob` 本身接受任意数量的模板类型参数。
|
||||
|
||||
```cpp
|
||||
template <template<class...> typename bob>
|
||||
struct foo {
|
||||
template<typename T>
|
||||
void bar(const bob<T>& arg) {
|
||||
std::cout << "size: " << arg.size() << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
foo<std::vector> f;
|
||||
std::vector<int> vec = {1, 2, 3, 4, 5};
|
||||
f.bar(vec);
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
在 `main` 函数中,我们使用 `std::vector` 实例化了 `foo`,将其作为 `bob` 的模板参数。这使我们能够创建一个通用的结构 `foo`,可以与任何接受任意数量类型参数的模板一起工作,例如 `std::vector`、`std::list` 或用户定义的模板。
|
||||
|
||||
### 9. 内联变量
|
||||
|
||||
C++17允许在类的定义内部定义变量为内联的,这可以帮助减小二进制大小,可能通过防止变量在多个转换单元中的重复副本来提高性能。
|
||||
|
||||
例子:
|
||||
|
||||
```cpp
|
||||
class MyClass {
|
||||
public:
|
||||
inline static int inlineVar = 42;
|
||||
};
|
||||
|
||||
int main() {
|
||||
int localVar = MyClass::inlineVar;
|
||||
}
|
||||
```
|
||||
|
||||
在这里,`inlineVar`是`MyClass`的内联静态成员变量。
|
||||
|
||||
### 10. 属性改进
|
||||
|
||||
C++17提供新的属性,并改进了已有的属性,允许开发人员为编译器提供更多的代码行为信息。
|
||||
|
||||
例子:
|
||||
|
||||
```cpp
|
||||
[[nodiscard]] int get_sum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main() {
|
||||
auto result = get_sum(1, 2);
|
||||
// 编译器可能会警告‘result’未使用
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,`[[nodiscard]]`是可以应用于函数的属性,表示其返回值不应该被调用者丢弃。
|
||||
|
||||
### 11. 嵌套命名空间
|
||||
|
||||
C++17通过折叠表达式增强了变参模板,使得在处理参数包时的代码更为简洁和表达明了。
|
||||
|
||||
例子:
|
||||
|
||||
```cpp
|
||||
// 外部命名空间
|
||||
namespace outer {
|
||||
// 内部命名空间
|
||||
namespace inner {
|
||||
void foo() {
|
||||
std::cout << "在内部命名空间中" << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
outer::inner::foo();
|
||||
|
||||
```
|
||||
|
||||
嵌套命名空间定义提供了一种将代码层次化组织的方式,提高了可读性和可维护性,尤其是在大型项目中。它们还通过提供更加结构化的命名空间层次结构来帮助避免命名冲突。
|
||||
|
||||
### 12. 字面量改进
|
||||
|
||||
C++17增强了字面量,包括对整数和浮点字面量的改进,以及对真和假字面量的支持。
|
||||
|
||||
例子:
|
||||
|
||||
```
|
||||
auto num = 123_456; // Underscore in integer literals
|
||||
auto pi = 3.1415_f; // Suffix for floating-point literals
|
||||
```
|
||||
|
||||
### 13. constexpr Lambda
|
||||
|
||||
C++17允许lambda函数成为constexpr,如果它们满足条件,就可以在需要编译时评估的上下文中使用,例如:
|
||||
|
||||
```cpp
|
||||
constexpr auto lambda = [](int x) { return x * 2; };
|
||||
static_assert(lambda(5) == 10);
|
||||
```
|
||||
|
||||
在这个例子中,`lambda`是一个constexpr lambda,它接受一个整数x作为参数,然后返回x的两倍。`static_assert`检查在编译时,`lambda(5)`的值是否等于10。
|
||||
|
||||
### 14. 捕获*this
|
||||
|
||||
在lambda中捕获*this变得更加简单,允许直接访问包含对象的成员。
|
||||
|
||||
```cpp
|
||||
class Foo {
|
||||
int data = 42;
|
||||
public:
|
||||
auto member_lambda() {
|
||||
return [*this] { std::cout << data << std::endl; };
|
||||
}
|
||||
};
|
||||
|
||||
// 使用
|
||||
Foo f;
|
||||
f.member_lambda()(); // 输出 "42"
|
||||
```
|
||||
|
||||
### 15. 扩展的if和switch语句
|
||||
|
||||
`if`或`switch`语句中的条件现在可以是任何表达式,不仅限于布尔条件。这使得控制流更加灵活,例如使用结构化绑定时:
|
||||
|
||||
```cpp
|
||||
if (const auto [it, inserted] = map.insert({"foo", bar}); inserted) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,`if`语句检查`inserted`变量是否为真,但条件还包括结构化绑定的赋值。
|
||||
|
||||
### 16. 泛化的基于范围的for循环
|
||||
|
||||
此改进支持不同于起始迭代器类型的标志或结束迭代器,这有助于处理以空终止的循环和其他类似情况。例如:
|
||||
|
||||
```cpp
|
||||
for (auto it = my_container.begin(); it != my_container.end(); ++it) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
在此例子中,`my_container`可能是使用不同类型的结束迭代器的容器,但循环仍然可以正确工作。
|
||||
|
||||
### 17. if constexpr
|
||||
|
||||
此特性通过允许编译器在编译时评估条件,从而实现更通用的代码。如果条件为真,则编译的代码中包含`if`块内的代码;否则,它将被丢弃。这可以通过在运行时删除不必要的分支来简化代码。例如:
|
||||
|
||||
```cpp
|
||||
if constexpr (std::is_same_v<T, int>) {
|
||||
// 用于int的特定代码
|
||||
} else {
|
||||
// 用于其他类型的代码
|
||||
}
|
||||
```
|
||||
|
||||
在这个例子中,`if constexpr`语句检查类型`T`是否为`int`,并相应地包含适当的代码。
|
||||
|
||||
### 总结
|
||||
|
||||
本节就先写这么多,其他内容下一节进行阐述。
|
||||
@@ -0,0 +1,118 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/ctad-class-template-argument-deduction/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 类模板参数推导 CTAD
|
||||
|
||||
## **引入**
|
||||
|
||||
C++模板元编程一直是C++开发者们熟知的一项功能,无论是初学者还是高级开发者都能够通过它编写具有类型参数的通用代码。随着C++17引入的类模板参数推导(CTAD),处理类模板的过程变得更加直观和灵活。
|
||||
|
||||
本节所有代码也会更新于社群中。
|
||||
|
||||
C++17引入CTAD会带来如下好处:
|
||||
|
||||
例如:这么复杂的代码
|
||||
|
||||
```
|
||||
std::vector<FooBar<int, const char*>> obj{a, b, c};
|
||||
```
|
||||
|
||||
我们只需要:
|
||||
|
||||
```
|
||||
std::vector obj{a, b, c};
|
||||
```
|
||||
|
||||
再比如:
|
||||
|
||||
```
|
||||
std::tuple<int>
|
||||
```
|
||||
|
||||
可以简化为:
|
||||
|
||||
```
|
||||
std::tuple t1{1};
|
||||
```
|
||||
|
||||
所以,咱们今天来看看CTAD。
|
||||
|
||||
CTAD全称是Class template argument deduction (CTAD),类模版参数推导,你给定编译器一个推导指南(deduction guide),我们便可以使用这个特性了。
|
||||
|
||||
如果不给定,如下面例子:
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
template <typename T, typename U>
|
||||
struct MyPair {
|
||||
T first{};
|
||||
U second{};
|
||||
};
|
||||
|
||||
int main() {
|
||||
MyPair<int, int> p1{1, 2};
|
||||
MyPair p2{1, 2};
|
||||
std::cout << p1.first << ", " << p1.second << std::endl;
|
||||
std::cout << p2.first << ", " << p2.second << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
对于p2,我们便会报错:
|
||||
|
||||
no viable constructor or deduction guide for deduction of template arguments of 'MyPair'
|
||||
|
||||
那么对于怎么修改呢?
|
||||
|
||||
只需要添加deduction guid即可,如下写法即可。
|
||||
|
||||
```
|
||||
template <typename T, typename U>
|
||||
MyPair(T, U) -> MyPair<T, U>;
|
||||
```
|
||||
|
||||
类模板参数推导(CTAD)通过允许编译器从构造函数参数中推导出模板参数,简化了类模板的实例化过程。在引入CTAD之前,开发者在实例化时必须明确指定模板参数。然而,通过CTAD,这种明确的指定变得不再必要,从而使代码更易读、易维护。
|
||||
|
||||
```
|
||||
template <typename T>
|
||||
class Add{
|
||||
private:
|
||||
T first;
|
||||
T second;
|
||||
public:
|
||||
Add() = default;
|
||||
Add(T first, T second): first_{first}, second_{second} {}
|
||||
T result() const { return first + second; }
|
||||
};
|
||||
|
||||
int main(){
|
||||
Add one(1,2); // T被推导为int
|
||||
Add two{1.245, 3.1415}; // T被推导为double
|
||||
Add three = {0.24f, 0.34f}; // T被推导为float
|
||||
}
|
||||
```
|
||||
|
||||
在上面的示例中,CTAD允许类型`T`基于构造函数参数被推导,消除了显式类型指定的需求。
|
||||
|
||||
## **非静态成员初始化**
|
||||
|
||||
但是有个场景用不了CTAD,那就是非静态成员初始化。例如:Test类中使用外面的MyPair就必须写全。
|
||||
|
||||
```
|
||||
template <typename T = int, typename U = int>
|
||||
struct MyPair {
|
||||
T first{};
|
||||
U second{};
|
||||
};
|
||||
|
||||
template <typename T, typename U>
|
||||
MyPair(T, U) -> MyPair<T, U>;
|
||||
|
||||
class Test {
|
||||
MyPair p4; // use of class template 'MyPair' requires template arguments; argument
|
||||
// deduction not allowed in non-static class member
|
||||
};
|
||||
```
|
||||
|
||||
在上面的例子中,我们定义了一个模板类`MyPair`,并在其中使用了CTAD。然而,当我们尝试在类`Test`中使用`MyPair`作为非静态成员时,由于非静态成员初始化的上下文,CTAD将无法正常工作,导致编译错误。在这种情况下,我们必须显式指定`MyPair`的模板参数。
|
||||
|
||||
我们可以看到在非静态成员初始化的上下文中,CTAD无法推导模板参数。因此,在类模板作为非静态成员时,开发者需要显式指定所有的模板参数。这一点需要在实际开发中特别注意,以确保代码的正确性和可维护性。
|
||||
170
site_extras/modern-cpp-cpp17-optional-ref.md
Normal file
170
site_extras/modern-cpp-cpp17-optional-ref.md
Normal file
@@ -0,0 +1,170 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/optional-ref/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 optional_ref
|
||||
|
||||
This should have been part 2 of my [comparison series](https://www.foonathan.net/blog/2018/06/20/equivalence-relations.html), and I have almost finished it, but due to university stuff I just haven’t found the time to polish it.
|
||||
|
||||
But the optional discussion started again, so I just wanted to *really* quickly share my raw thoughts on the topic. In case you are lucky and don’t know what I mean: `std::optional<T&>` doesn’t compile right now, because the behavior of assignment wasn’t clear (even though it actually is). There are basically four questions in the discussion I want to answer:
|
||||
|
||||
1. Is `std::optional<T&>` the same as a pointer?
|
||||
2. Do we need `std::optional<T&>`?
|
||||
3. Should the assignment operator rebind or assign through?
|
||||
4. Should it even have an assignment operator?
|
||||
|
||||
tl;dr: no, I don’t, rebind, no.
|
||||
|
||||
|
||||
|
||||
## 1. Is `std::optional<T&>` the same as a pointer?
|
||||
|
||||
What does it even mean to have an “optional `T&`”? Well, it is a `T&` that can also be `nullptr`.
|
||||
|
||||
So a pointer, a `T*`?
|
||||
|
||||
No, not really.
|
||||
|
||||
There is a more important difference between `T&` and `T*` besides the nullability: A `T&` has implicit creation and access, a `T*` explicit creation and access.
|
||||
|
||||
If you have an object, you can just silently bind a reference to it. And if you have a reference, you can just treat it *as if* it was the object. Whereas for pointers, you need to explicitly use `&obj` and `*ptr`.
|
||||
|
||||
And this difference is huge: It means `const T&` can be used for function parameters without any additional syntax issues:
|
||||
|
||||
```cpp
|
||||
void print(const T& obj);
|
||||
…
|
||||
T obj = …;
|
||||
print(obj);
|
||||
```
|
||||
|
||||
You wouldn’t want to use a `const T*` as now the call side has to do extra work, it has to use the unnecessary `&obj`. This is just awkward.
|
||||
|
||||
> It is a different situation if the function might modify the object through the pointer/reference, or store a pointer/reference in a persistent location.
|
||||
|
||||
So naturally, if you want to have an optional argument, you wouldn’t want to use a pointer for the same reason: Why now introduce unnecessary syntactic overhead? It shouldn’t matter to the caller.
|
||||
|
||||
So `std::optional<T&>` is not the same as `T*`: It would have implicit creation syntax, not explicit.
|
||||
|
||||
What `std::optional<T&>` cannot have, however, is implicit access. Not only is it not implementable currently, it is also fundamentally impossible: For `std::optional<T&>` to have implicit access syntax, every operation on it would delegate to the referring object. This includes checking whether it refers to an object! Any `.has_value()` or `!opt` would forward to the referring object. This means that an explicit syntax is required, otherwise you’re just checking whether the optional has an object that is null.
|
||||
|
||||
A more thorough analysis can be found in the first twenty minutes of my [Rethinking Pointers](https://jonathanmueller.dev/talk/cppnow2018) talk at C++Now earlier this year.
|
||||
|
||||
## 2. Do we need `std::optional<T&>`?
|
||||
|
||||
As `std::optional<T&>` isn’t the same as `T*`, we need to look at the situations where we use `T&` and think about whether we need an optional version there.
|
||||
|
||||
Luckily, I did exactly that in my [Rethinking Pointers](https://jonathanmueller.dev/talk/cppnow2018) talk.
|
||||
|
||||
### Function Parameters
|
||||
|
||||
```cpp
|
||||
void print(const T& obj);
|
||||
void sort(Container& cont);
|
||||
```
|
||||
|
||||
Here we want to either avoid a copy, or modify an argument in-place. If we want to have optional arguments, a `std::optional<T&>` is a solution. However, simply overloading the function works as well.
|
||||
|
||||
### Getter Functions
|
||||
|
||||
```cpp
|
||||
const std::string& person::name() const;
|
||||
```
|
||||
|
||||
Again, we want to avoid a copy.
|
||||
|
||||
If the returned value might not be available, we could just use non-reference `std::optional`, but have to pay for an additional copy. Or we could narrow the contact and add a precondition requiring the object to be there, but this is less type safe.
|
||||
|
||||
### LValue Functions
|
||||
|
||||
```cpp
|
||||
T& std::vector::operator[](std::size_t index);
|
||||
T& std::optional<T>::value();
|
||||
```
|
||||
|
||||
Here we *absolutely* need an lvalue as a return type. This is the motivation behind references, so we use them. However, optional references wouldn’t work – we’d loose implicit access, which is incompatible with the conventional usage of operators.
|
||||
|
||||
### Range-based `for` loops
|
||||
|
||||
```cpp
|
||||
for (auto& cur : container)
|
||||
…
|
||||
```
|
||||
|
||||
Here optional references are not required.
|
||||
|
||||
### Lifetime extension when calling a function (experts only):
|
||||
|
||||
```cpp
|
||||
const std::string& name = p.name();
|
||||
// use `name` multiple times
|
||||
```
|
||||
|
||||
Lifetime extension only works with normal references.
|
||||
|
||||
------
|
||||
|
||||
That’s it, that are all the situations where you should use a `T&`. The only situations where it might be feasible to have a `std::optional<T&>` are function parameters and getters where we want to avoid a copy. This is not such a compelling use-case.
|
||||
|
||||
## 3. Should the assignment operator rebind or assign through?
|
||||
|
||||
Assignment *fundamentally* is an optimization of copy. It should just do the same thing as “destroy the current object” and “copy a new one over”.
|
||||
|
||||
So when we write `opt_a = opt_b`, it will modify `opt_a` so it is a copy of `opt_b`. This is true for all `T`, including `T&`: If `opt_b` is a reference to `my_obj`, then `opt_a` will also be a reference to `my_obj`, even it was a reference to `other_obj` before. So the copy assignment operator does a rebind operation.
|
||||
|
||||
Now `std::optional` also has an assignment operator taking a `T`: This assignment operator is an optimization of the constructor taking a `T`.
|
||||
|
||||
> Read more about assignment as an optimization in [this blog post](https://www.foonathan.net/blog/2017/10/11/explicit-assignment.html) I’ve written some time ago.
|
||||
|
||||
As such, it will destroy the current object, if there is any, and then create the new object inside it. However, as it is an optimization, it will use `T::operator=` if the optional has a value already. The assignment operator of `T` might be more efficient than “destroy” followed by “construct”.
|
||||
|
||||
But note that it only does that, because it assumes that the assignment operator of `T` is an optimization of copy! If you provide a `T` where `rocket = launch` means “launch the rocket” this will fail. But this isn’t optional’s fault, your type is just stupid!
|
||||
|
||||
And one such stupid type is `T&`: The assignment operator of `T&` is not an optimization of “destroy” followed by “copy”. This is because references *have no assignment operator*: Every operation you do on a reference is actually done on the object it refers to. This includes assignment, so the assignment operator will assign the value, it assigns through.
|
||||
|
||||
Now some people think that having that behavior in the `operator=` of `optional<T&>` itself is even a possibility they need to consider.
|
||||
|
||||
It isn’t.
|
||||
|
||||
It absolutely isn’t.
|
||||
|
||||
Ignoring any other counter argument, those semantics would lead to confusion as `operator=` would do completely different things depending on the state of the `optional`!
|
||||
|
||||
```cpp
|
||||
std::optional<T&> opt = …;
|
||||
|
||||
T obj;
|
||||
opt = obj;
|
||||
// if opt was empty before, it will now refer to obj
|
||||
// if opt wasn't empty before, it will now refer to an object with the same value as obj
|
||||
|
||||
return opt; // so this is legal only if the optional wasn't empty before
|
||||
```
|
||||
|
||||
There is no precedent for an assignment operator that behaves like this, because an assignment operator shouldn’t behave like this.
|
||||
|
||||
## 4. Should it even have an assignment operator?
|
||||
|
||||
Whenever we use a `T&` we don’t need to modify the reference itself – after all, we can’t. So when we replace the `T&` with a `std::optional<T&>` there is no need to mutate the `std::optional<T&>` either.
|
||||
|
||||
Now the “assign through” people of `std::optional<T&>` argue that this behavior is consistent with `T&`.
|
||||
|
||||
It isn’t, as references aren’t assignable.
|
||||
|
||||
Sure, writing `ref = obj` *compiles*, but it is not an assignment. It only works because *every* operation done on a reference is done on the object it refers to.
|
||||
|
||||
Now as I said before, when we have a nullable reference we can’t do that, because then we would have no syntax to check for nullability. So the only way to be truly consistent with `T&` would be if `std::optional<T&>` would have no modifying operators. It shouldn’t have an `operator=`, an `emplace()` function, etc. After all, `T&` is immutable, so `std::optional<T&>` should be as well.
|
||||
|
||||
If you are in a situation where you need to mutate a `std::optional<T&>`, you didn’t *want* an `std::optional<T&>`, you wanted a pointer. Because then you store the optional in a persistent location and should have used an explicit creation syntax to make it obvious. More on that in [my talk](https://jonathanmueller.dev/talk/cppnow2018).
|
||||
|
||||
Note that, if you have a `std::optional<T&>` without modifiers, it behaves nothing like an `std::optional<T>` – because a `T&` behaves nothing like a `T`. Just like generic code can’t handle `T&`, it also wouldn’t handle `std::optional<T&>`.
|
||||
|
||||
So we shouldn’t spell “optional `T&`” as `std::optional<T&>`, it should be spelt differently. I’d argue it should be called `std::optional_arg<T>`, because that reflects the actual use case it’s going to get.
|
||||
|
||||
## Conclusion
|
||||
|
||||
In my opinion we don’t need `std::optional<T&>`. It is a weird type with only very few use cases.
|
||||
|
||||
If the committee decides that adding `std::optional<T&>` is worth the effort, it should be an immutable `std::optional`, just like references are. For the actual uses cases of `std::optional<T&>`, just like the use cases of `T&`, it doesn’t actually matter.
|
||||
|
||||
Note that a type that behaves like a `T*`, but isn’t, is useful: A `T*` can do a lot of different things, so it might be a good idea to add a distinct type that explicitly models just one of the things it does. In my [type_safe](https://github.com/foonathan/type_safe) library, for example, I have an `ts::optional_ref<T>`, which is like a `T*` and not like a nullable `T&`. However, it definitely shouldn’t be spelled `std::optional<T&>`, because it is not a `T&`.
|
||||
|
||||
More details, again, in my [Rethinking Pointers](https://jonathanmueller.dev/talk/cppnow2018) talk.
|
||||
58
site_extras/modern-cpp-cpp17-std-variant.md
Normal file
58
site_extras/modern-cpp-cpp17-std-variant.md
Normal file
@@ -0,0 +1,58 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/std-variant/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 std::variant
|
||||
|
||||
最近想出一些有趣的问题,做一个小总结,你能回答上来几个?
|
||||
|
||||
注:完整答案会在星球揭秘。
|
||||
|
||||
**问题1:std::variant构造函数会调用几个类型构造,1个?2个?n个?**
|
||||
|
||||
```cpp
|
||||
std::variant<std::string, int> a1;
|
||||
std::variant<X, Y> a2;
|
||||
```
|
||||
|
||||
**相关问题:**
|
||||
|
||||
1. `std::variant` 的默认构造行为如何?
|
||||
2. 当 `std::variant` 包含类型不具有默认构造函数时会发生什么?
|
||||
3. 如何指定 `std::variant` 的初始值类型?
|
||||
|
||||
**问题2:下面代码可以正常运行吗?如果可以运行说明理由,否则给出几个解决方案。**
|
||||
|
||||
```cpp
|
||||
struct X {
|
||||
X(int v) : v_(v) {}
|
||||
int v_;
|
||||
};
|
||||
|
||||
struct Y {
|
||||
Y(double v) : v_(v) {}
|
||||
double v_;
|
||||
};
|
||||
|
||||
std::variant<X, Y> a1;
|
||||
```
|
||||
|
||||
**相关问题:**
|
||||
|
||||
1. 如何为 `std::variant` 添加具有默认构造函数的类型?
|
||||
2. 当 `std::variant` 的类型列表中没有默认构造函数时,有哪些解决方案?
|
||||
3. 如何显式构造 `std::variant` 以避免默认构造问题?
|
||||
|
||||
**问题3:什么是monostate,解决了什么问题?**
|
||||
|
||||
**相关问题:**
|
||||
|
||||
1. 如何在 `std::variant` 中使用 `std::monostate`?
|
||||
2. `std::monostate` 的引入对 `std::variant` 的设计有哪些影响?
|
||||
3. 在什么情况下使用 `std::monostate` 是合适的?
|
||||
|
||||
**问题4:defer_lock_t、try_to_lock_t、adopt_lock_t这三者的区别是什么?什么场景下使用?**
|
||||
|
||||
**相关问题:**
|
||||
|
||||
1. `defer_lock_t` 的使用场景和实现机制是什么?
|
||||
2. `try_to_lock_t` 如何处理互斥锁的尝试锁定?
|
||||
3. `adopt_lock_t` 在接管已有锁的所有权时有什么注意事项?
|
||||
117
site_extras/modern-cpp-cpp17-structured-bindings.md
Normal file
117
site_extras/modern-cpp-cpp17-structured-bindings.md
Normal file
@@ -0,0 +1,117 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/structured-bindings/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 结构化绑定
|
||||
|
||||
在聊结构化绑定之前,有几个面试问题,看看你会不会?
|
||||
|
||||
- 如何使用结构化绑定访问自定义类的私有成员?
|
||||
|
||||
- 如何使用结构化绑定修改自定义类的成员呢?
|
||||
|
||||
这几个题目估计没几个人能答上来,题目与答案网上也都没有,基于这些问题,我们引出本文的内容:如何为自定义类型支持结构化绑定,里面有哪些坑?
|
||||
|
||||
**注:懒人版,答案与代码已放星球。**
|
||||
|
||||
为了让本文的内容更加丝滑,从示例出发。
|
||||
|
||||
## 1.自定义类型
|
||||
|
||||
如果给定一个类:
|
||||
|
||||
```cpp
|
||||
struct Foo {
|
||||
Foo(int64_t id, std::string data) : id_(id), data_(std::move(data)) {}
|
||||
void Print() { std::cout << "id = " << id_ << ", data = " << data_ << std::endl; }
|
||||
|
||||
private:
|
||||
int64_t id_;
|
||||
std::string data_;
|
||||
};
|
||||
```
|
||||
|
||||
要让下面这个代码运行起来:
|
||||
|
||||
```cpp
|
||||
int main() {
|
||||
Foo f{12, "hello world"};
|
||||
const auto& [id, data] = f;
|
||||
std::cout << "id = " << id << ", data = " << data << std::endl;
|
||||
f.Print();
|
||||
}
|
||||
```
|
||||
|
||||
如果直接运行会编译:
|
||||
|
||||
```cpp
|
||||
cannot decompose inaccessible member 'Foo::id_' of 'const Foo'
|
||||
42 | const auto& [id, data] = f;
|
||||
```
|
||||
|
||||
那么怎么做呢?
|
||||
|
||||
## 2.支持结构化绑定
|
||||
|
||||
这个问题我们使用两个步骤:
|
||||
|
||||
1.特化 `std::tuple_size` 和 `std::tuple_element`
|
||||
|
||||
```cpp
|
||||
namespace std {
|
||||
template <>
|
||||
struct tuple_size<Foo> : std::integral_constant<std::size_t, 2> {};
|
||||
|
||||
template <>
|
||||
struct tuple_element<0, Foo> {
|
||||
using type = int64_t;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct tuple_element<1, Foo> {
|
||||
using type = std::string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
2.为上面的结构体添加友元get函数,然后实现即可:
|
||||
|
||||
```cpp
|
||||
template <std::size_t Index>
|
||||
decltype(auto) get(const Foo& f);
|
||||
|
||||
template <>
|
||||
decltype(auto) get<0>(const Foo& f) {
|
||||
return f.id_;
|
||||
}
|
||||
|
||||
template <>
|
||||
decltype(auto) get<1>(const Foo& f) {
|
||||
return f.data_;
|
||||
}
|
||||
```
|
||||
|
||||
此时便可以正常的工作了,得到输出:
|
||||
|
||||
```cpp
|
||||
id = 12, data = hello world
|
||||
id = 12, data = hello world
|
||||
```
|
||||
|
||||
最后,抛出几个问题:
|
||||
|
||||
- 上面提供的是只读访问,如果在访问的时候修改const auto &会发生什么?
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
auto& [id, data] = f;
|
||||
```
|
||||
|
||||
- 如何支持对类成员的修改访问?
|
||||
|
||||
即,让这个语句能够正常运行
|
||||
|
||||
```cpp
|
||||
auto& [id, data] = f;
|
||||
```
|
||||
|
||||
好了,本节完,欢迎留言区交流。
|
||||
74
site_extras/modern-cpp-cpp17-template-auto-deduction.md
Normal file
74
site_extras/modern-cpp-cpp17-template-auto-deduction.md
Normal file
@@ -0,0 +1,74 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/template-auto-deduction/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 模板 auto 推导
|
||||
|
||||
## C++之万物皆可auto
|
||||
|
||||
C++17引入了许多旨在提高代码表达性并减少模板代码冗余的功能。其中一个显著的增强是使用`auto`关键字声明非类型模板参数的能力。在某些场景,这个特性特别方便,因为它消除了显式类型声明的需要。以下我将会引入我在工作中,也就是数据库当中如何使用这一特性!
|
||||
|
||||
从实践中学习,本节的完整源码会上传至星球,感兴趣戳尾页二维码。
|
||||
|
||||
## 在C++17中使用`auto`的非类型模板参数
|
||||
|
||||
### 在数据库场景中进行排序
|
||||
|
||||
考虑一个与数据库相关的类`Foo`,你希望根据枚举表示的特定顺序进行排序:
|
||||
|
||||
```cpp
|
||||
enum class SortOrder { Ascending, Descending };
|
||||
```
|
||||
|
||||
你有不同排序顺序的`Foo`实例:
|
||||
|
||||
```cpp
|
||||
Foo<SortOrder::Ascending> f1;
|
||||
Foo<SortOrder::Descending> f2;
|
||||
```
|
||||
|
||||
### 以前的实现方式
|
||||
|
||||
在C++17之前,我们可能会这样实现:
|
||||
|
||||
```cpp
|
||||
template <typename U, template <U> class T, U K>
|
||||
auto GetSortOrder(const T<K>&) {
|
||||
return K;
|
||||
}
|
||||
```
|
||||
|
||||
然而,这可能会导致错误,因为编译器无法推断模板参数'U'。
|
||||
|
||||
### 现在的简化方式
|
||||
|
||||
在C++17之后,对于非类型模板参数,我们可以使用`auto`关键字来取代:
|
||||
|
||||
```cpp
|
||||
template <template <auto> class T, auto K>
|
||||
auto GetSortOrder(const T<K>&) {
|
||||
return K;
|
||||
}
|
||||
```
|
||||
|
||||
这种方式更为简便,使得我们无需显式指定类型即可使用非类型模板参数。
|
||||
|
||||
### integral_constant的简化
|
||||
|
||||
以前,我们可能使用以下方式实现integral_constant:
|
||||
|
||||
```cpp
|
||||
template <typename _Tp, _Tp __v>
|
||||
struct integral_constant {}
|
||||
```
|
||||
|
||||
而现在只需:
|
||||
|
||||
```cpp
|
||||
template <auto __v>
|
||||
struct integral_constant {}
|
||||
```
|
||||
|
||||
这种简化使得代码更为清晰和易读。
|
||||
|
||||
## 结论
|
||||
|
||||
C++17引入的`auto`关键字用于非类型模板参数的声明极大地简化了模板代码。通过消除繁琐的类型声明,我们能够更加直观地表达代码意图,提高代码的可读性和可维护性。在处理排序等场景时,这一特性尤为有用,让我们更专注于问题的本质,而不是模板参数的细节。
|
||||
101
site_extras/modern-cpp-cpp17-variable-templates.md
Normal file
101
site_extras/modern-cpp-cpp17-variable-templates.md
Normal file
@@ -0,0 +1,101 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp17/variable-templates/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++17 变量模板
|
||||
|
||||
## C++那些事之变量模版
|
||||
|
||||
|
||||
|
||||
在编写模板代码时,我们经常需要定义和使用各种类型特征(type traits)。这些类型特征通常用于在编译期对类型进行判断,STL 提供的 `std::is_const`、`std::is_same` 和 `std::is_reference` 就是这样的例子。通过这些特征,开发者可以根据类型属性进行编译期决策。
|
||||
|
||||
本文将介绍如何利用 **C++14 变量模板(variable templates)** 来简化类型特征的编写,并提供一个简单的示例。
|
||||
|
||||
### C++11
|
||||
|
||||
在 C++11 中,编写类型特征通常要使用 `struct` 或 `std::integral_constant` 来封装布尔值。例如,我们要编写一个判断类型是否为 `float` 的类型特征 `is_float`,可以通过如下方式实现:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
struct is_float {
|
||||
static constexpr bool value = std::is_same<T, float>::value;
|
||||
};
|
||||
```
|
||||
|
||||
或者稍微简洁一点,使用类型别名和 `std::integral_constant`:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
using is_float = std::integral_constant<bool, std::is_same<T, float>::value>;
|
||||
```
|
||||
|
||||
尽管这比直接使用 `struct` 更简洁,最终我们仍然是在定义一个类型,而不是直接得到布尔值。要使用这个特征时,需要通过 `::value` 成员来获取布尔值:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
void test(T t){
|
||||
if (is_float<T>::value){
|
||||
std::cout << "I'm a float" << std::endl;
|
||||
} else {
|
||||
std::cout << "I'm not a float" << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
这样虽然可以工作,但仍存在两方面的不足:
|
||||
1. 每次使用类型特征时都要访问 `::value`。
|
||||
2. 定义新的类型特征时必须声明新的类型或类型别名,增加了代码冗余。
|
||||
|
||||
### C++14 变量模板的引入
|
||||
|
||||
C++14 引入了 **变量模板**,允许我们直接定义依赖于类型的变量。这一特性简化了类型特征的编写,使得我们不再需要使用类型别名或 `struct` 来封装布尔值,而是可以直接定义布尔值。
|
||||
|
||||
重写后的 `is_float` 特征如下:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
constexpr bool is_float = std::is_same<T, float>::value;
|
||||
```
|
||||
|
||||
这种方式显得更加简洁明了,去除了不必要的代码。使用起来也更方便:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
void test(T t){
|
||||
if (is_float<T>){
|
||||
std::cout << "I'm a float" << std::endl;
|
||||
} else {
|
||||
std::cout << "I'm not a float" << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
相比之前的写法,使用变量模板后,**不再需要通过 `::value` 来访问布尔值**,代码更加简洁直观。
|
||||
|
||||
### 变量模板的优势
|
||||
|
||||
1. **减少冗余代码**:变量模板允许我们直接定义基于类型的变量,避免了使用 `struct` 或 `std::integral_constant` 封装布尔值的冗余代码。
|
||||
2. **提高可读性**:变量模板通过简化语法,使代码更清晰,尤其是在编写大量类型特征时。
|
||||
3. **支持模板特化**:与类型别名模板不同,变量模板可以进行特化,无论是全特化还是部分特化。我们可以为特定类型定义专门的逻辑,而不必担心扩展性问题。
|
||||
|
||||
### C++17 的进一步改进
|
||||
|
||||
C++17 进一步扩展了变量模板的应用,为每个类型特征提供了变量模板的辅助工具。例如,`std::is_same` 引入了 `std::is_same_v` 变量模板,用于简化访问类型特征值:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
constexpr bool is_float = std::is_same_v<T, float>;
|
||||
```
|
||||
|
||||
通过这种方式,类型特征的使用更加简洁,开发者可以直接利用变量模板而无需每次访问 `::value`。
|
||||
|
||||
### 实际案例
|
||||
|
||||
这项特性在实际领域使用的挺多的,例如:数据库当中分配不同大小的内存块,我们可以通过模版初始化不同类型的块大小。
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
constexpr size_t block_size = 1024; // 默认大小
|
||||
|
||||
template <>
|
||||
constexpr size_t block_size<double> = 2048; // double 类型需要更多内存
|
||||
```
|
||||
229
site_extras/modern-cpp-cpp20-cpp-coroutines.md
Normal file
229
site_extras/modern-cpp-cpp20-cpp-coroutines.md
Normal file
@@ -0,0 +1,229 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp-coroutines/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 协程入门
|
||||
|
||||
## 1.什么是Coroutines
|
||||
|
||||
自C++20之后,C++终于支持协程了,C++ 23应该带来额外的支持,至少应该涵盖最常见的用例。
|
||||
|
||||
**协程**(英语:coroutine)是计算机程序的一类组件,推广了[协作式多任务](https://zh.wikipedia.org/wiki/协作式多任务)的[子例程](https://zh.wikipedia.org/wiki/子例程),允许执行被挂起与被恢复。相对子例程而言,协程更为一般和灵活,但在实践中使用没有子例程那样广泛。协程更适合于用来实现彼此熟悉的程序组件,如[协作式多任务](https://zh.wikipedia.org/wiki/协作式多任务)、[异常处理](https://zh.wikipedia.org/wiki/异常处理)、[事件循环](https://zh.wikipedia.org/wiki/事件循环)、[迭代器](https://zh.wikipedia.org/wiki/迭代器)、[无限列表](https://zh.wikipedia.org/wiki/惰性求值)和[管道](https://zh.wikipedia.org/wiki/管道_(软件))。
|
||||
|
||||
> 来自维基百科的一段话描述了协程的基本思想。
|
||||
|
||||
从C++角度,可以简单理解协程是**任何包含co_return, co_yield或co_await的函数**。
|
||||
|
||||
目前C++20协程是函数对象上的语法糖,编译器将围绕协程生成一个代码框架。此代码依赖于用户定义的**promise types**。可能会在C++23之后对此有所变动,不过在此之前,我们先按照C++20的规则来,需要自己编写这些类型。
|
||||
|
||||
前面提到co_return、co_yield、co_await,这些将在未来章节进行阐述。
|
||||
|
||||
## 2.Step By Step Coroutine
|
||||
|
||||
接下来,我们从一个简单的coroutine例子入手,下面这个协程不会做任何事情,我们称它为HelloTask courtine。
|
||||
|
||||
```cpp
|
||||
#include <coroutine>
|
||||
struct HelloTask {
|
||||
struct promise_type {
|
||||
HelloTask get_return_object() { return {}; }
|
||||
std::suspend_never initial_suspend() { return {}; }
|
||||
std::suspend_never final_suspend() noexcept { return {}; }
|
||||
void return_void() {}
|
||||
void unhandled_exception() {}
|
||||
};
|
||||
};
|
||||
HelloTask myCoroutine() {
|
||||
co_return; // make it a coroutine
|
||||
}
|
||||
int main() {
|
||||
HelloTask x = myCoroutine();
|
||||
}
|
||||
```
|
||||
|
||||
编译运行这段代码:
|
||||
|
||||
```cpp
|
||||
g++ hello.cpp -fcoroutines -std=c++20
|
||||
```
|
||||
|
||||
需要你的编译器支持C++20特性。
|
||||
|
||||
从上到下来浏览一遍这段HelloWorld程序跟平时的开发有何不同。
|
||||
|
||||
### 2.1 头文件
|
||||
|
||||
首先是头文件引入了`coroutine`,这里我直接拿gcc-10的源码,看看到底做了什么事情。
|
||||
|
||||
> https://github.com/gcc-mirror/gcc/blob/releases/gcc-10/libstdc++-v3/include/std/coroutine
|
||||
|
||||
内容包括如下:
|
||||
|
||||
```cpp
|
||||
// 用于发现协程promise_type的特征类型
|
||||
// 核心代码:using promise_type = typename _Result::promise_type;
|
||||
1.coroutine_traits
|
||||
|
||||
// 协程句柄,用于管理暂停或执行的协程以及Promise
|
||||
2.coroutine_handle
|
||||
// coroutine_handle全特化版本 是其他特化的公开基类。它保有handle的底层 地址。
|
||||
2.1 coroutine_handle<void>
|
||||
|
||||
// coroutine_handle泛化版本
|
||||
2.2 template <typename _Promise>
|
||||
struct coroutine_handle : coroutine_handle<>
|
||||
|
||||
|
||||
// coroutine_handle全特化版本 处理无操作协程
|
||||
2.3 template <>
|
||||
struct coroutine_handle<noop_coroutine_promise> : public coroutine_handle<>
|
||||
3.平凡多可等待对象 Trivial awaitables
|
||||
// await表达式应该暂停
|
||||
3.1 suspend_always
|
||||
// await表达式不应该暂停
|
||||
3.2 suspend_never
|
||||
```
|
||||
|
||||
可以看到里面包含了很多专有的术语:
|
||||
|
||||
- coroutine_handle
|
||||
- Promise
|
||||
- awaitable
|
||||
|
||||
等等。
|
||||
|
||||
后面所讲的协程内容都是围绕这些来展开的。
|
||||
|
||||
## 2.2 Promise
|
||||
|
||||
我们继续上面的HelloTask,会发现里面有这么一段:
|
||||
|
||||
```cpp
|
||||
struct HelloTask {
|
||||
struct promise_type {
|
||||
HelloTask get_return_object() { return {}; }
|
||||
std::suspend_never initial_suspend() { return {}; }
|
||||
std::suspend_never final_suspend() noexcept { return {}; }
|
||||
void return_void() {}
|
||||
void unhandled_exception() {}
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
那么问题来了,为何这里要写promise_type?
|
||||
|
||||
之所以写promise_type是因为我们在上述2.1节提到了handle,当编译器创建协程的handle时,需要指定该协程对象的promise_type,所以所有的协程对象基本都有一个HelloTask::promise_type结构。仔细的朋友可能就非常懂了,这里传递promise_type过去,在Handle里面会解析出来,从而去判断当前用户自定义的协程对象的行为。
|
||||
|
||||
进一步的看看promise_type里面有什么,这里面的内容都是固定的,随着后续的内容越来越多,所涉及的函数也便是越来越多,例如这里使用的是`return_void`,那么当后面使用co_return返回对象时,便会使用另外一个函数了。
|
||||
|
||||
**get_return_object**是可以返回当前用户自定义对象的,这里是不做任何操作,承接上文2.1,我们可以使用coroutine_handle来做。
|
||||
|
||||
```cpp
|
||||
struct promise_type {
|
||||
using Handle = std::coroutine_handle<promise_type>;
|
||||
HelloTask get_return_object() {
|
||||
return HelloTask{Handle::from_promise(*this)};
|
||||
}
|
||||
// other member function
|
||||
}
|
||||
```
|
||||
|
||||
可以看到这里使用了coroutine_handle的from_promise成员去构造了一个对象出来。
|
||||
|
||||
**initial_suspend**:告诉编译器协程是否应该在第一次执行时保持挂起,或者表示协程实例化时是否保持挂起。
|
||||
|
||||
**final_suspend**:与initial_suspend相反,在协程函数体完成后,在协程的末尾有一个final_suspend。这使你有机会进行额外的清理。
|
||||
|
||||
这两个都返回awaitable,这里采用了头文件中的suspend_always,当然也可以用户自定义awaitable,这个会在后面文章进行阐述。
|
||||
|
||||
suspend_always与suspend_never的源码如下:
|
||||
|
||||
```cpp
|
||||
struct suspend_always
|
||||
{
|
||||
constexpr bool await_ready() const noexcept { return false; }
|
||||
|
||||
constexpr void await_suspend(coroutine_handle<>) const noexcept {}
|
||||
|
||||
constexpr void await_resume() const noexcept {}
|
||||
};
|
||||
|
||||
struct suspend_never
|
||||
{
|
||||
constexpr bool await_ready() const noexcept { return true; }
|
||||
|
||||
constexpr void await_suspend(coroutine_handle<>) const noexcept {}
|
||||
|
||||
constexpr void await_resume() const noexcept {}
|
||||
};
|
||||
```
|
||||
|
||||
这里面包含了几个成员,
|
||||
|
||||
- await_ready
|
||||
- 如果知道结果已经准备就绪是否同步完成?
|
||||
- await_suspend
|
||||
- **返回值可以是bool 、void、coroutine handle。**
|
||||
- 这里返回的是void,则立即将控制返回到当前Coroutine的 caller/resumer (此Coroutine仍然被暂停),否则如果等待_suspend返回bool,true表示控制权交给caller/resumer,表示false恢复当前的coroutine。关于返回coroutine handle在后面文章进行阐述。
|
||||
- await_resume
|
||||
- 它的结果是整个co_await表达式的结果。所以返回值不一定是void,还可以是自定义对象之类的。
|
||||
|
||||
**return_void**: 当使用`co_return;`时,将调用return_void。
|
||||
|
||||
**unhandled_exception**:用于捕获异常。
|
||||
|
||||
最后,还差一个创建coroutine一步,根据一开始的定义协程是**任何包含co_return, co_yield或co_await的函数**。因此便有了:
|
||||
|
||||
```cpp
|
||||
HelloTask myCoroutine() {
|
||||
co_return; // make it a coroutine
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 整体流程
|
||||
|
||||
整个调用流程是什么呢?本节来详细阐述一下上述代码的执行逻辑,开始之前我们改一下代码,加上一些print操作:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <coroutine>
|
||||
struct HelloTask {
|
||||
struct promise_type {
|
||||
HelloTask get_return_object() { std::cout << "get_return_object" << std::endl; return { }; }
|
||||
std::suspend_never initial_suspend() { std::cout << "initial_suspend" << std::endl; return {}; }
|
||||
std::suspend_never final_suspend() noexcept { std::cout << "final_suspend" << std::endl;return {}; }
|
||||
void return_void() { std::cout << "return_void" << std::endl; }
|
||||
void unhandled_exception() { std::cout << "unhandled_exception" << std::endl; }
|
||||
};
|
||||
};
|
||||
HelloTask myCoroutine() {
|
||||
std::cout << "create coroutine" << std::endl;
|
||||
co_return; // make it a coroutine
|
||||
}
|
||||
int main() {
|
||||
std::cout << "start main" << std::endl;
|
||||
HelloTask x = myCoroutine();
|
||||
std::cout << "end main" << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
此时输出:
|
||||
|
||||
```cpp
|
||||
start main
|
||||
get_return_object
|
||||
initial_suspend
|
||||
create coroutine
|
||||
return_void
|
||||
final_suspend
|
||||
end main
|
||||
```
|
||||
|
||||
流程如下:
|
||||
|
||||
- start main
|
||||
- 在堆上分配coutine对象,构造promise,调用promise.get_return_object返回当前对象(此时输出了get_return_object),这里这么做的目的是把结果保存到了局部变量里面。
|
||||
- promise.initial_suspend,此时输出initial_suspend,这里会触发co_await,输出create coroutine,执行协程体后,调用co_return。
|
||||
- co_return调用promise.return_void 输出return_void。
|
||||
- 最终,promise.final_suspend输出final_suspend。
|
||||
- end main
|
||||
|
||||
关于协程的相关内容还有特别多的东西,本节为开篇,后续将持续更新~
|
||||
112
site_extras/modern-cpp-cpp20-cpp20-channel.md
Normal file
112
site_extras/modern-cpp-cpp20-cpp20-channel.md
Normal file
@@ -0,0 +1,112 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-channel/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 channel 实战
|
||||
|
||||
## C++20实战之channel
|
||||
|
||||
继前面两节的直播,讲解了thread、jthread、stop_token、stop_source、stop_callback、cv、cv_any等的用法与底层实现,那么如何基于这些知识实现一个小项目呢?
|
||||
|
||||
于是引出了这篇,写一个channel出来。
|
||||
|
||||
## 1.设计
|
||||
|
||||
### 1.1 接口设计
|
||||
|
||||
接口层面我们期望与通用的channel一样,能够一次性创建一个发送、接收的channel。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
auto [sender, receiver] = make_channel<int>();
|
||||
```
|
||||
|
||||
这里的实现可以通过类似make_unique提供一个对外的接口,返回值通过C++17的结构化绑定获取,此时便得到了两个channel。
|
||||
|
||||
最核心的两个接口:发送与接收。
|
||||
|
||||
- 发送
|
||||
|
||||
```cpp
|
||||
sender.send(counter++);
|
||||
```
|
||||
|
||||
- 接收
|
||||
|
||||
```
|
||||
auto value = receiver.recv();
|
||||
```
|
||||
|
||||
除此之外,还可以在析构函数的时候提供一个shutdown接口,当send、recv阻塞的时候能够被唤醒释放。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
bool shutdown() {
|
||||
if (!state_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
light_city_lock lk(state_->mutex);
|
||||
if (source_.stop_requested()) {
|
||||
return false;
|
||||
}
|
||||
source_.request_stop();
|
||||
state_->cv.notify_all();
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 内部队列设计
|
||||
|
||||
内部队列可以参考前面几天发的如何设计一个线程安全的多生产者多消费者队列,这里可以内部维护一个state,然后带上queue、mutex、cv_any。
|
||||
|
||||
```cpp
|
||||
struct State {
|
||||
std::queue<T> queue;
|
||||
std::mutex mutex;
|
||||
// C++11 condition_variable_any
|
||||
std::condition_variable_any cv;
|
||||
};
|
||||
```
|
||||
|
||||
## 2.使用
|
||||
|
||||
使用起来就非常容易,只需要make出来两个channel,然后去send与recv即可。
|
||||
|
||||
这里我使用了jthread + stop_token来完成这个工作,例如:
|
||||
|
||||
```cpp
|
||||
std::jthread sender_thread(
|
||||
[](Channel<int> sender, std::stop_token token) {
|
||||
int counter = 0;
|
||||
while (!token.stop_requested()) {
|
||||
sender.send(counter++);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
},
|
||||
std::move(sender), token);
|
||||
```
|
||||
|
||||
接收端线程类似,在执行的差不多时,我们可以使用
|
||||
|
||||
```
|
||||
stop_source.request_stop();
|
||||
```
|
||||
|
||||
至此,便模拟了一个channel,发送端发送数据,接收端接收数据即可。
|
||||
|
||||
运行示例:
|
||||
|
||||
```cpp
|
||||
➜ channel ./a.out
|
||||
Received: 0
|
||||
Received: 1
|
||||
Received: 2
|
||||
Received: 3
|
||||
Received: 4
|
||||
Received: 5
|
||||
Received: 6
|
||||
Received: 7
|
||||
Received: 8
|
||||
Received: 9
|
||||
```
|
||||
300
site_extras/modern-cpp-cpp20-cpp20-concepts.md
Normal file
300
site_extras/modern-cpp-cpp20-cpp20-concepts.md
Normal file
@@ -0,0 +1,300 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-concepts/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 Concepts 概念
|
||||
|
||||
[TOC]
|
||||
|
||||
C++20引入了concept(概念),是对模板参数(编译时评估)的一组约束。你可以将它们用于类模板和函数模板来控制函数重载和特化。一些优点包括:
|
||||
|
||||
- 对模版参数强制类型约束
|
||||
- 提高代码可读性(替换了较长的SFINAE代码)
|
||||
- 提供更友好的报错信息
|
||||
- 通过限制可以使用的类型来防止意外的模板实例化
|
||||
|
||||
以一个比较简单加法为例。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
struct Foo {};
|
||||
|
||||
template <typename T>
|
||||
T Add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::cout << Add(1, 2) << std::endl;
|
||||
Foo f1, f2;
|
||||
std::cout << Add(f1, f2) << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
对于Foo来说,是不支持加法的,于此同时也是不可以直接`std::cout << `,因此在编译时报一大堆错误,包含`operator<<`与`operator+`,但这并不是我们期望的错误信息,我们比较期望的是编译器给我们最直观的错误信息,即:这个结构体能不能相加。
|
||||
|
||||
```
|
||||
add.cc: In function 'int main()':
|
||||
add.cc:13:13: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Foo')
|
||||
13 | std::cout << Add(f1, f2) << std::endl;
|
||||
| ~~~~~~~~~ ^~ ~~~~~~~~~~~
|
||||
| | |
|
||||
| | Foo
|
||||
| std::ostream {aka std::basic_ostream<char>}
|
||||
In file included from /usr/local/Cellar/gcc/13.2.0/include/c++/13/iostream:41,
|
||||
from add.cc:1:
|
||||
/usr/local/Cellar/gcc/13.2.0/include/c++/13/ostream:110:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(__ostream_type& (*)(__ostream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]'
|
||||
110 | operator<<(__ostream_type& (*__pf)(__ostream_type&))
|
||||
|
||||
/usr/local/Cellar/gcc/13.2.0/include/c++/13/ostream:801:5: note: template argument deduction/substitution failed:
|
||||
/usr/local/Cellar/gcc/13.2.0/include/c++/13/ostream: In substitution of 'template<class _Ostream, class _Tp> _Ostream&& std::operator<<(_Ostream&&, const _Tp&) [with _Ostream = std::basic_ostream<char>&; _Tp = Foo]':
|
||||
add.cc:13:26: required from here
|
||||
/usr/local/Cellar/gcc/13.2.0/include/c++/13/ostream:801:5: error: no type named 'type' in 'struct std::enable_if<false, void>'
|
||||
add.cc: In instantiation of 'T Add(T, T) [with T = Foo]':
|
||||
add.cc:13:19: required from here
|
||||
add.cc:7:12: error: no match for 'operator+' (operand types are 'Foo' and 'Foo')
|
||||
7 | return a + b;
|
||||
| ~~^~~
|
||||
```
|
||||
|
||||
当我们使用concept实现之后:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
concept Addable = requires(T a, T b) { a + b; };
|
||||
|
||||
template <typename T>
|
||||
requires Addable<T>
|
||||
T Add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
便可以得到我们关心的编译错误:
|
||||
|
||||
```cpp
|
||||
add_concept.cc: In function 'int main()':
|
||||
add_concept.cc:17:19: error: no matching function for call to 'Add(Foo&, Foo&)'
|
||||
17 | std::cout << Add(f1, f2) << std::endl;
|
||||
| ~~~^~~~~~~~
|
||||
add_concept.cc:10:3: note: candidate: 'template<class T> requires Addable<T> T Add(T, T)'
|
||||
10 | T Add(T a, T b) {
|
||||
| ^~~
|
||||
add_concept.cc:10:3: note: template argument deduction/substitution failed:
|
||||
add_concept.cc:10:3: note: constraints not satisfied
|
||||
add_concept.cc: In substitution of 'template<class T> requires Addable<T> T Add(T, T) [with T = Foo]':
|
||||
add_concept.cc:17:19: required from here
|
||||
add_concept.cc:6:9: required for the satisfaction of 'Addable<T>' [with T = Foo]
|
||||
add_concept.cc:6:19: in requirements with 'T a', 'T b' [with T = Foo]
|
||||
add_concept.cc:6:42: note: the required expression '(a + b)' is invalid
|
||||
6 | concept Addable = requires(T a, T b) { a + b; };
|
||||
| ~~^~~
|
||||
```
|
||||
|
||||
下面,我们来针对上面这个例子深入学习concept语法。
|
||||
|
||||
## 1.concept语法
|
||||
|
||||
语法:
|
||||
|
||||
```
|
||||
template <template-parameter-list>
|
||||
concept concept-name = constraint-expression;
|
||||
```
|
||||
|
||||
我们来对比一下实际的例子,Addable是concept-name,constraint-expression是`requires(T a, T b) { a + b; }`。
|
||||
|
||||
```
|
||||
template <typename T>
|
||||
concept Addable = requires(T a, T b) { a + b; };
|
||||
```
|
||||
|
||||
使用方式为:
|
||||
|
||||
```
|
||||
#include <concepts>
|
||||
```
|
||||
|
||||
这个concept可以放在多个地方,如下:
|
||||
|
||||
- typename的位置
|
||||
- requires后面
|
||||
- auto前面
|
||||
|
||||
### 1.1 替换typename
|
||||
|
||||
约束模版参数,替换typename。
|
||||
|
||||
```cpp
|
||||
// template <typename T> typename->Addable
|
||||
template <Addable T>
|
||||
T Add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 requires关键字
|
||||
|
||||
我们在函数模板中使用 requires 关键字。 它可以访问我们的模板T是否是可以相加的,如果模板可以处理相加,它将返回 true。
|
||||
|
||||
requires可以放在模版中,也可以放在函数之后,但是不可以放在类之后。于此同时它有两个写法:
|
||||
|
||||
- requires 条件
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
requires Addable<T>
|
||||
T Add(T a, T b) { ... }
|
||||
```
|
||||
|
||||
- requires 表达式
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
concept Addable = requires(T a, T b) { a + b; };
|
||||
```
|
||||
|
||||
#### 1.2.1 放在模版中
|
||||
|
||||
函数:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
requires Addable<T>
|
||||
T Add(T a, T b) {
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
类:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
requires Addable<T>
|
||||
class Bar {
|
||||
public:
|
||||
T Add(T a, T b) { return a + b; }
|
||||
};
|
||||
```
|
||||
|
||||
#### 1.2.2 函数尾随 Requires 子句
|
||||
|
||||
函数:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
T Add(T a, T b)
|
||||
requires Addable<T>
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
对于类则不支持这种写法,会报错:error: expected unqualified-id before 'requires' 28 | requires Addable<T>
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
class Bar requires Addable<T>
|
||||
{
|
||||
public:
|
||||
T Add(T a, T b) { return a + b; }
|
||||
};
|
||||
```
|
||||
|
||||
#### 1.2.3 requires基本示例
|
||||
|
||||
以数据库当中的类型为例,数据库中有不同类型,我们将其划分为:null、binary、number等,我们想要对传递的类型执行打印操作,于是有了下面的示例:
|
||||
|
||||
```cpp
|
||||
#include <concepts>
|
||||
|
||||
class NumberType {};
|
||||
class BaseBinaryType {};
|
||||
class NullType {};
|
||||
class FloatingPointType : public NumberType {};
|
||||
class IntegerType : public NumberType {};
|
||||
class BinaryType: public BaseBinaryType {};
|
||||
|
||||
template <typename T>
|
||||
requires std::is_base_of_v<NumberType, T> || std::is_base_of_v<BaseBinaryType, T>
|
||||
void PrintValue(T v) {}
|
||||
|
||||
int main() {
|
||||
PrintValue(FloatingPointType{});
|
||||
PrintValue(NullType{});
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
对于requires我们可以使用`||`,上面示例中出现了NullType,它不满足`requires`,因此会编译出现:
|
||||
|
||||
```cpp
|
||||
concept_requires.cc:16:13: error: no matching function for call to 'PrintValue(NullType)'
|
||||
16 | PrintValue(NullType{});
|
||||
| ~~~~~~~~~~^~~~~~~~~~~~
|
||||
concept_requires.cc:12:6: note: candidate: 'template<class T> requires (is_base_of_v<NumberType, T>) || (is_base_of_v<BaseBinaryType, T>) void PrintValue(T)'
|
||||
12 | void PrintValue(T v) {}
|
||||
| ^~~~~~~~~~
|
||||
concept_requires.cc:12:6: note: template argument deduction/substitution failed:
|
||||
concept_requires.cc:12:6: note: constraints not satisfied
|
||||
concept_requires.cc: In substitution of 'template<class T> requires (is_base_of_v<NumberType, T>) || (is_base_of_v<BaseBinaryType, T>) void PrintValue(T) [with T = NullType]':
|
||||
concept_requires.cc:16:13: required from here
|
||||
concept_requires.cc:12:6: required by the constraints of 'template<class T> requires (is_base_of_v<NumberType, T>) || (is_base_of_v<BaseBinaryType, T>) void PrintValue(T)'
|
||||
concept_requires.cc:11:45: note: no operand of the disjunction is satisfied
|
||||
11 | requires std::is_base_of_v<NumberType, T> || std::is_base_of_v<BaseBinaryType, T>
|
||||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
### 1.3 concept与auto
|
||||
|
||||
当auto出现时,我们可以将其与concept一起使用,例如:
|
||||
|
||||
```cpp
|
||||
auto add(auto x, auto y) {
|
||||
return x + y;
|
||||
}
|
||||
```
|
||||
|
||||
我们可以变为:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
concept Addable = requires(T a, T b) { a + b; };
|
||||
|
||||
auto add2(Addable auto x, Addable auto y) {
|
||||
return x + y;
|
||||
}
|
||||
```
|
||||
|
||||
编译时会出现:
|
||||
|
||||
```cpp
|
||||
concept_auto.cc:17:20: error: no matching function for call to 'add2(Foo&, Foo&)'
|
||||
17 | std::cout << add2(f1, f2) << std::endl;
|
||||
| ~~~~^~~~~~~~
|
||||
concept_auto.cc:10:6: note: candidate: 'template<class auto:18, class auto:19> requires (Addable<auto:18>) && (Addable<auto:19>) auto add2(auto:18, auto:19)'
|
||||
10 | auto add2(Addable auto x, Addable auto y) {
|
||||
| ^~~~
|
||||
concept_auto.cc:10:6: note: template argument deduction/substitution failed:
|
||||
concept_auto.cc:10:6: note: constraints not satisfied
|
||||
concept_auto.cc: In substitution of 'template<class auto:18, class auto:19> requires (Addable<auto:18>) && (Addable<auto:19>) auto add2(auto:18, auto:19) [with auto:18 = Foo; auto:19 = Foo]':
|
||||
concept_auto.cc:17:20: required from here
|
||||
concept_auto.cc:8:9: required for the satisfaction of 'Addable<auto:18>' [with auto:18 = Foo]
|
||||
concept_auto.cc:8:19: in requirements with 'T a', 'T b' [with T = Foo]
|
||||
concept_auto.cc:8:42: note: the required expression '(a + b)' is invalid
|
||||
8 | concept Addable = requires(T a, T b) { a + b; };
|
||||
```
|
||||
|
||||
## 2.编译器支持
|
||||
|
||||
需要GCC(10.0+),Clang(10.0+),编译选项:`-std=c++20`/`-std=c++2a`
|
||||
|
||||
> https://en.cppreference.com/w/cpp/compiler_support
|
||||
|
||||
## 3.总结
|
||||
|
||||
自C++20提供的concept之后,我们不再需要enable_if/SFINAE的机制、函数重载来做一些模版约束检查了,使用concept可以帮你搞定这个操作,它提供了一种更清晰和强大的模板参数约束机制,使得模板代码更易于编写、理解和维护。通过在编译时进行类型检查,它有助于提高代码的稳健性和可读性。
|
||||
66
site_extras/modern-cpp-cpp20-cpp20-constexpr-comma.md
Normal file
66
site_extras/modern-cpp-cpp20-cpp20-constexpr-comma.md
Normal file
@@ -0,0 +1,66 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-constexpr-comma/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 constexpr 与逗号表达式
|
||||
|
||||
### C++20那些事之constexpr与comma expr
|
||||
|
||||
C++20 引入了多项新特性,进一步增强了编译时能力和代码安全性。本文将深入探讨两项重要的变更:**constexpr 函数中的异常处理**以及**下标运算符中逗号运算符的弃用**。
|
||||
|
||||
**注:懒人版,本节的代码示例与相关文档已更新在星球,感兴趣加入即可。**
|
||||
|
||||
#### 1. constexpr 函数中支持 try-catch 异常处理的变更
|
||||
|
||||
在 C++20 之前,`constexpr` 函数中不能使用 `try-catch` 块,这一限制阻碍了一些标准库容器如 `std::array` 的编译时处理能力。C++20 对此进行了改进,**允许在 `constexpr` 函数中使用 `try-catch` 块,并且在常量表达式的上下文中忽略这些异常处理结构**。当在常量表达式计算中抛出异常时,编译器会报错。
|
||||
|
||||
这项改动的主要目的是让标准库中的容器能够支持 `constexpr`,例如 `std::array`,同时为将来在编译时支持更多异常处理提供了基础。
|
||||
|
||||
**示例**:
|
||||
|
||||
```cpp
|
||||
constexpr int SafeDivide(int a, int b) {
|
||||
if (b == 0) {
|
||||
throw std::runtime_error("Division by zero!"); // 当除数为0时抛出异常
|
||||
}
|
||||
return a / b;
|
||||
}
|
||||
|
||||
constexpr int ComputeQuotient(int x) {
|
||||
try {
|
||||
return SafeDivide(100, x); // 尝试除法运算
|
||||
} catch (const std::runtime_error&) {
|
||||
return -1; // 捕获除零异常并返回 -1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上面代码在C++20之前编译不过,那么C++20对这个行为是什么呢,可以猜一下下面两个结果:
|
||||
|
||||
```cpp
|
||||
static_assert(ComputeQuotient(25) == 4);
|
||||
static_assert(ComputeQuotient(0) == -1);
|
||||
```
|
||||
|
||||
#### 2. 下标运算符中的逗号运算符弃用
|
||||
|
||||
C++20 的另一项变更是**弃用在下标运算符中使用逗号运算符**。在早期的 C++ 版本中,表达式 `array[x, y]` 中,逗号运算符会使 `y` 作为下标传递给数组或容器,而 `x` 被忽略。然而,这种用法会导致代码不易理解,并且妨碍未来多维数组的实现。因此,自 C++20 起,**下标运算符中的逗号运算符被弃用**,除非使用括号明确指定优先级,如 `array[(x, y)]`。
|
||||
|
||||
**示例代码**:
|
||||
|
||||
```cpp
|
||||
// arr[i, j] = 10; // C++17 中合法,C++20 中弃用
|
||||
arr[(i, j)] = 10; // 使用括号以明确逗号的优先级
|
||||
```
|
||||
|
||||
在这个例子中,`arr[(i, j)]` 使用了括号以明确逗号运算符的优先级,确保 `j` 作为下标传递给数组。在 C++17 中,`arr[i, j]` 是允许的,但在 C++20 中,这样的用法会触发弃用警告。通过这种方式可以确保代码的行为一致,并符合 C++20 的新标准。
|
||||
|
||||
如果使用了逗号运算符编译器将会警告:
|
||||
|
||||
```cpp
|
||||
common.cc:9:10: warning: top-level comma expression in array subscript is deprecated [-Wcomma-subscript]
|
||||
9 | arr[i, j] = 10; // C++17 中合法,C++20 中弃用
|
||||
| ^
|
||||
```
|
||||
|
||||
### 总结
|
||||
|
||||
C++20 中的这些变更,特别是 `constexpr` 函数中的异常处理支持和下标运算符中逗号运算符的弃用,都是为了提升编译时能力和代码的可读性。如果你的代码依赖这些旧特性,建议及时进行调整,以适应 C++20 的新标准。
|
||||
70
site_extras/modern-cpp-cpp20-cpp20-endian.md
Normal file
70
site_extras/modern-cpp-cpp20-cpp20-endian.md
Normal file
@@ -0,0 +1,70 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-endian/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 字节序 endian
|
||||
|
||||
在面试的时候,字节序通常是一个非常重要的考点,会考察:
|
||||
|
||||
- 大小端概念
|
||||
- 如何判断大小端
|
||||
- 主机字节序
|
||||
- 网络字节序
|
||||
- 等等
|
||||
|
||||
,那么判别方式其实有很多种,例如:
|
||||
|
||||
- C++20的endian
|
||||
- union
|
||||
- 地址转换
|
||||
- htons
|
||||
|
||||
那么本节就来阐述一下C++20的大小端使用与基础知识。
|
||||
|
||||
**注:懒人版,4种方式判别大小端源码已放星球,感兴趣获取即可。**
|
||||
|
||||
## 1.字节序基础
|
||||
|
||||
系统的字节序指的是字节在内存中存储或通过网络传输的顺序。大端系统在最低内存地址存储最高有效字节(MSB)。这在各种网络协议中用于通过网络发送数据,也称为网络字节序。在小端系统中,最低有效字节(LSB)存储在最低内存地址。例如,十六进制数0x12345678的存储方式如下:
|
||||
|
||||
- 大端:
|
||||
|
||||
```
|
||||
地址 | 值
|
||||
|
||||
n | 0x12
|
||||
n + 1 | 0x34
|
||||
n + 2 | 0x56
|
||||
n + 3 | 0x78
|
||||
```
|
||||
|
||||
- 小端
|
||||
|
||||
```
|
||||
地址 | 值
|
||||
|
||||
n | 0x78
|
||||
n + 1 | 0x56
|
||||
n + 2 | 0x34
|
||||
n + 3 | 0x12
|
||||
```
|
||||
|
||||
根据架构的不同,不同的系统可能是大端或小端的主机字节序。
|
||||
|
||||
## 2.字节序的重要性
|
||||
|
||||
那么,这为什么重要呢?如果你需要通过网络发送数据,那么你需要确保它以网络字节序传输。在大多数情况下,你的主机字节序将是小端,这意味着你需要在传输数据之前反转字节的顺序。
|
||||
|
||||
## 3.检查字节序
|
||||
|
||||
C++20引入了一种更简单且更可移植的方式来检查字节序,即std::endian。你可以使用std::endian::native检查系统的主机字节序。下面是一个简单的例子:
|
||||
|
||||
```cpp
|
||||
void checkEndianness() {
|
||||
if constexpr (std::endian::native == std::endian::little) {
|
||||
std::cout << "小端" << std::endl;
|
||||
} else if constexpr (std::endian::native == std::endian::big) {
|
||||
std::cout << "大端" << std::endl;
|
||||
} else {
|
||||
std::cout << "未知" << std::endl;
|
||||
}
|
||||
}
|
||||
```
|
||||
91
site_extras/modern-cpp-cpp20-cpp20-lambda-part1.md
Normal file
91
site_extras/modern-cpp-cpp20-cpp20-lambda-part1.md
Normal file
@@ -0,0 +1,91 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-lambda-part1/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 Lambda 表达式(上)
|
||||
|
||||
## C++20之lambda模版
|
||||
|
||||
C++14 支持泛型 lambda 表达式,这使得 lambda 可以接受任意类型的参数,例如:
|
||||
|
||||
```cpp
|
||||
auto func = [](auto a, auto b) {
|
||||
return a + b;
|
||||
};
|
||||
```
|
||||
|
||||
会被展开为:
|
||||
|
||||
```cpp
|
||||
struct Func {
|
||||
template <typename T1, typename T2>
|
||||
auto operator()(T1 a, T2 b) const {
|
||||
return a + b;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
但是却无法做到下面几种展开式:
|
||||
|
||||
第一种:相同类型
|
||||
|
||||
````cpp
|
||||
template <class T>
|
||||
auto operator()(T t1, T t2) const;
|
||||
````
|
||||
|
||||
第二种:只有std::array
|
||||
|
||||
```cpp
|
||||
template <class T, std::size_t N>
|
||||
auto operator()(std::array<T, N> const &) const;
|
||||
```
|
||||
|
||||
第三种:没有推导
|
||||
|
||||
```
|
||||
template <class T>
|
||||
auto operator()() const;
|
||||
```
|
||||
|
||||
C++14 lambdas 很好,但是 C++20 允许我们轻松实现这些情况。C++20允许lambda表达式在定义中使用模版类型参数,以下是基本的语法:
|
||||
|
||||
```cpp
|
||||
[]<typename T>(){}
|
||||
```
|
||||
|
||||
下面通过几个示例说明它的好处。
|
||||
|
||||
## 1.类型限定
|
||||
|
||||
像下面这种例子,C++14我们可以写出下面的代码,但是我们在使用的时候传递进来的不一定是一个vector,那么与预期的行为就会不一致,从而产生错误。
|
||||
|
||||
```cpp
|
||||
auto print = [](auto vec) {
|
||||
for (auto x : vec) {
|
||||
std::cout << x << std::endl;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
C++20之后,我们可以限定其类型:
|
||||
|
||||
```cpp
|
||||
auto print2 = []<typename T>(std::vector<T>& vec){
|
||||
//使用 std::vector<T> 执行操作
|
||||
};
|
||||
```
|
||||
|
||||
那么问题来了,出一个面试题目:你知道C++14中为了限定vector,怎么才能保证安全呢?
|
||||
|
||||
## 2.完美转发
|
||||
|
||||
在C++20中你可以非常轻松的使用完美转发,例如:
|
||||
|
||||
```cpp
|
||||
auto lambdaFunc = []<typename T>(T&& number) {
|
||||
processFunction(std::forward<T>(number));
|
||||
};
|
||||
```
|
||||
|
||||
那么问题来了,相比于C++14来说,有什么优势?或者说C++14实现完美转发需要做什么?
|
||||
|
||||
> 本节完
|
||||
486
site_extras/modern-cpp-cpp20-cpp20-modules.md
Normal file
486
site_extras/modern-cpp-cpp20-cpp20-modules.md
Normal file
@@ -0,0 +1,486 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-modules/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 模块 Modules
|
||||
|
||||
[TOC]
|
||||
|
||||
当我们使用自己编写的头文件或者第三方库时,通常会用到`#include `指令来引入**库**,这是大家经常使用的一种方式。这种方法,实际上是将一个源文件(头文件)的所有代码拷到另一个文件中。
|
||||
|
||||
那么,这会面临如下问题:
|
||||
|
||||
- 源文件可能在同一目标中被包含多次,因此我们通常会使用`#pragma once`或者`#ifndef`,从而防止源文件在同一翻译单元中被包含多次。
|
||||
- 代码的拷贝会导致编译时间更长,一旦修改一个头文件,便会导致间接包含这个头文件的一些文件被重新编译。
|
||||
- `#include `顺序问题,有时候会遇到莫名其妙的编译问题。
|
||||
|
||||
C++20引入了一种替代 `#include 指令`的新方式,称为模块。
|
||||
|
||||
下面来深入学习一下模块。
|
||||
|
||||
## 1.模块单元
|
||||
|
||||
C++模块由一个或多个翻译单元(tu)组成,其中包含用于模块声明的特定关键字。这样的翻译单元称为模块单元。
|
||||
|
||||
非模块单元的翻译单元被认为是全局模块的一部分,全局模块是匿名的,没有接口,并且包含常规的非模块代码。
|
||||
|
||||
### 1.1 Global Module Fragment
|
||||
|
||||
模块单元可以以全局模块片段作为**前缀**,当无法导入头文件时(特别是当头文件使用预处理宏作为配置时),该全局模块片段可以直接使用原来的代码。
|
||||
|
||||
例如:下面代码中`module;`到`export module Foo;`中间为global module fragment。
|
||||
|
||||
```cpp
|
||||
module;
|
||||
#include <iostream>
|
||||
#ifdef Say
|
||||
void hello();
|
||||
#endif
|
||||
export module Foo;
|
||||
// purivew
|
||||
void world();
|
||||
```
|
||||
|
||||
必须要注意的一点是:**如果该模块有全局模块片段,那么第一个声明必须是`module;`**,也就是说当把这个声明放在其他位置会出错。
|
||||
|
||||
### 1.2 purview
|
||||
|
||||
purview可以理解为模块的整个范围。从模块声明开始,一直延伸到翻译单元的末尾。
|
||||
|
||||
例如:hello不在,world、GetData都在purview。
|
||||
|
||||
```cpp
|
||||
module;
|
||||
void hello();
|
||||
// <- 这里不在Foo模块的purview内
|
||||
export module Foo;
|
||||
// <- 在Foo模块的purview内
|
||||
void world();
|
||||
export void GetData();
|
||||
|
||||
```
|
||||
|
||||
### 1.3 Private module fragment
|
||||
|
||||
主模块接口单元可以用私有模块片段作为**后缀**,该部分只能出现在主模块接口单元中,如果存在,则它出现的模块单元必须是该模块的唯一单元。 其目的是将模块的接口和实现封装在单个翻译单元中,而不暴露实现细节。
|
||||
|
||||
例如:我想要创建一个Shape,计算其面积。
|
||||
|
||||
对外只需要暴露一个创建具体Shape的接口,调用共同的计算面积接口,于是我们可以写出如下模块。
|
||||
|
||||
```cpp
|
||||
export module Shape;
|
||||
|
||||
export class Shape {
|
||||
public:
|
||||
virtual double CalculateArea() = 0;
|
||||
};
|
||||
|
||||
export { std::shared_ptr<Shape> CreateRectangle(double length, double width); }
|
||||
|
||||
|
||||
module :private; // here
|
||||
|
||||
class Rectangle : public Shape {
|
||||
private:
|
||||
double length;
|
||||
double width;
|
||||
|
||||
public:
|
||||
Rectangle(double l, double w) : length(l), width(w) {}
|
||||
|
||||
double CalculateArea() override { return length * width; }
|
||||
};
|
||||
|
||||
std::shared_ptr<Shape> CreateRectangle(double length, double width) {
|
||||
return std::make_shared<Rectangle>(length, width);
|
||||
}
|
||||
```
|
||||
|
||||
将内部的细节全部放在private里面吗,我自己的g++版本是13,目前还不支持,会报如下错误:
|
||||
|
||||
gcc目前的支持情况,可以戳这里
|
||||
|
||||
> https://gcc.gnu.org/projects/cxx-status.html
|
||||
|
||||
```cpp
|
||||
shape.cppm:14:1: sorry, unimplemented: private module fragment
|
||||
14 | module :private;
|
||||
```
|
||||
|
||||
本地的clang是16版本,测试了一下是可以正常运行!
|
||||
|
||||
```cpp
|
||||
➜ clang++ -std=c++20 shape.cppm --precompile -o shape.pcm
|
||||
➜ clang++ -std=c++20 shape.cc -fprebuilt-module-path=. shape.pcm -o shape
|
||||
➜ ./shape
|
||||
area is 2
|
||||
```
|
||||
|
||||
上面三个部分,全局和私有模块片段对于模块的存在来说不是必需的,purview是模块必需的部分。
|
||||
|
||||
## 2.模块使用
|
||||
|
||||
### 2.1 创建模块
|
||||
|
||||
创建模块类似于我们定义一个头文件,它也有一个文件,一般命名后缀是.cppm。我们只需要在这个文件中使用`export`与`module`关键字,后面跟上模块名,这样便创建一个可导出模块。例如:
|
||||
|
||||
```cpp
|
||||
// foo.cppm
|
||||
export module foo;
|
||||
|
||||
// main.cc
|
||||
import foo;
|
||||
```
|
||||
|
||||
`export`关键字可以用在类、变量等地方,通常有下面两种写法:
|
||||
|
||||
```cpp
|
||||
export void func();
|
||||
|
||||
export {
|
||||
void func();
|
||||
constexpr double PI{3.14};
|
||||
};
|
||||
```
|
||||
|
||||
一种写法是export关键字放在常见声明前面,另外一种写法是导出块,类似于namespace写法,可以导出多个内容。
|
||||
|
||||
### 2.2 导出
|
||||
|
||||
这里就会涉及到一个重要问题,可以导出什么?
|
||||
|
||||
- variables, classes, structs, functions, namespaces, template functions/classes, concepts可以被导出
|
||||
- 内部链接不可导出,如static变量与函数,匿名namespace。
|
||||
|
||||
```cpp
|
||||
export static constexpr double PI = 3.14; // 不可导出
|
||||
```
|
||||
|
||||
- 导出声明必须发生在命名空间级别
|
||||
|
||||
```cpp
|
||||
namespace {
|
||||
export void print_no_export() { // 匿名命名空间,不可导出
|
||||
std::cout << "print no export" << std::endl;
|
||||
}
|
||||
};
|
||||
namespace light {
|
||||
export void print_export() { // ok
|
||||
std::cout << "print export" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
struct Foo {
|
||||
export int a; // 不能导出成员变量
|
||||
};
|
||||
```
|
||||
|
||||
- 导出命名空间会隐式导出其中的所有内容
|
||||
|
||||
```cpp
|
||||
export class Rectangle {
|
||||
private:
|
||||
double length;
|
||||
double width;
|
||||
public:
|
||||
Rectangle(double l, double w) : length(l), width(w) {}
|
||||
|
||||
double CalculateArea() { return length * width; } // 隐式导出
|
||||
};
|
||||
|
||||
export namespace {
|
||||
void print_export() { // 隐式导出
|
||||
std::cout << "print export" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
void func(); // 隐式导出
|
||||
constexpr double PI{3.14}; // 隐式导出
|
||||
};
|
||||
```
|
||||
|
||||
- 导出实体的第一个声明必须是导出声明。 后续声明和定义不需要有 export 关键字。
|
||||
|
||||
```cpp
|
||||
export class Foo; // ok
|
||||
export class Foo; // ok,只是会冗余
|
||||
|
||||
class Foo { // ok,隐式export
|
||||
public:
|
||||
void print() { std::cout << "this is foo" << std::endl; }
|
||||
};
|
||||
|
||||
class Bar; // not export
|
||||
export class Bar; // 无效,第一个声明已经是不可导出,后续的不可导出
|
||||
|
||||
|
||||
Foo f; // ok
|
||||
f.print(); // ok
|
||||
Bar b; // not ok
|
||||
```
|
||||
|
||||
- 非导出模块不可导出
|
||||
|
||||
```cpp
|
||||
module foo;
|
||||
|
||||
export void print { } // error: 'export' may only occur after a module interface declaration
|
||||
```
|
||||
|
||||
### 2.3 导入
|
||||
|
||||
与之对应的便是导入,导入也有一些规则,例如:
|
||||
|
||||
- 不可导入自身
|
||||
|
||||
- 在模块单元中,所有导入必须出现在该模块单元中的任何声明之前。 不能在模块单元中的任意点导入。
|
||||
|
||||
```cpp
|
||||
void func() {}
|
||||
import shape; // error: post-module-declaration imports must be contiguous
|
||||
|
||||
---------------
|
||||
import shape; // ok
|
||||
void func() {}
|
||||
```
|
||||
|
||||
- 仅允许全局范围导入
|
||||
|
||||
```cpp
|
||||
namespace light {
|
||||
import shape; // not ok
|
||||
};
|
||||
```
|
||||
|
||||
- 不允许循环导入
|
||||
|
||||
```cpp
|
||||
// shape.cppm
|
||||
export module shape;
|
||||
import circle; // 循环导入
|
||||
|
||||
// circle.cppm
|
||||
import shape;
|
||||
```
|
||||
|
||||
### 2.4 模块中的include
|
||||
|
||||
`#include <iostream>`在模块中如何使用呢?
|
||||
|
||||
#### 2.4.1 purview区`#include`
|
||||
|
||||
使用import替换`#include`
|
||||
|
||||
```cpp
|
||||
export module foo;
|
||||
import <iostream>;
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
g++-13编译如下,可以通过`c++-system-header`后面跟iostream来编译出`gcm`。
|
||||
|
||||
```cpp
|
||||
g++-13 -std=c++20 -fmodules-ts -x c++-system-header iostream
|
||||
g++-13 -fmodules-ts -std=c++20 -x c++ shape.cppm circle.cppm shape.cc
|
||||
```
|
||||
|
||||
如果是自己的头文件,例如:`consts.h`,发现可以直接放在模块里面去`#include`,例如:
|
||||
|
||||
```cpp
|
||||
export module foo;
|
||||
#include "consts.h"
|
||||
```
|
||||
|
||||
### 2.4.2 Global Module Fragment区`#inlcude`
|
||||
|
||||
对于`#include`以及宏都可以直接放在这个区使用,例如:
|
||||
|
||||
```cpp
|
||||
module;
|
||||
#ifdef
|
||||
#include <iostream>
|
||||
#endif
|
||||
export module foo;
|
||||
```
|
||||
|
||||
## 3.模块分解
|
||||
|
||||
当我们想将一个大模块分解成更小的模块时,我们可以使用以下两种方法:
|
||||
|
||||
- 模块分区。
|
||||
- 即允许我们将模块分解为多个文件。 但是,这对使用者来说实际上是不可见的,使用时正常导入模块即可。
|
||||
- 子模块。
|
||||
- 即允许我们将较大的模块分解为任意数量的子模块的层次结构。使用者可以选择导入整个模块,或者只导入特定的子模块。
|
||||
|
||||
### 3.1 模块分区
|
||||
|
||||
语法:
|
||||
|
||||
```cpp
|
||||
export module <module-name>:<part-name>;
|
||||
import :<part-name>; // 可以在import前面添加export导出该分区接口
|
||||
```
|
||||
|
||||
例如:我有一个shape,对外使用的时候只需要`import shape`,然后调用对应的接口即可,这里分别使用了circle分区与rectangle分区的接口。
|
||||
|
||||
```cpp
|
||||
import shape;
|
||||
|
||||
int main() {
|
||||
DrawCircle();
|
||||
DrawRectangle();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
shape是有两个分区,一个是circle,一个是rectangle,于是模块shape.cppm内容为:
|
||||
|
||||
```cpp
|
||||
export module shape;
|
||||
|
||||
export import :circle;
|
||||
export import :rectangle;
|
||||
```
|
||||
|
||||
两个子分区内容为:
|
||||
|
||||
```cpp
|
||||
// circle.cppm
|
||||
module;
|
||||
#include <iostream>
|
||||
export module shape:circle;
|
||||
export void DrawCircle() { std::cout << "draw circle" << std::endl; }
|
||||
|
||||
--------------
|
||||
// rectangle.cppm
|
||||
|
||||
module;
|
||||
#include <iostream>
|
||||
export module shape:rectangle;
|
||||
export void DrawRectangle() { std::cout << "draw rectangle" << std::endl; }
|
||||
```
|
||||
|
||||
当我使用clang与g++编译后发现,clang-16编译报错,不支持。
|
||||
|
||||
```cpp
|
||||
error: sorry, module partitions are not yet supported
|
||||
```
|
||||
|
||||
g++-13支持,需要注意编译的时候按照子分区->主分区的顺序进行编译,不然就会出错。
|
||||
|
||||
```cpp
|
||||
➜ g++-13 -fmodules-ts -std=c++20 -x c++ shape.cppm circle.cppm rectangle.cppm shape.cc
|
||||
shape:circle: error: failed to read compiled module: No such file or directory
|
||||
shape:circle: note: compiled module file is 'gcm.cache/shape-circle.gcm'
|
||||
shape:circle: note: imports must be built before being imported
|
||||
shape:circle: fatal error: returning to the gate for a mechanical issue
|
||||
```
|
||||
|
||||
应该改为:
|
||||
|
||||
```cpp
|
||||
g++ -fmodules-ts -std=c++20 -x c++ circle.cppm rectangle.cppm shape.cppm shape.cc
|
||||
```
|
||||
|
||||
### 3.2 子模块
|
||||
|
||||
语法:
|
||||
|
||||
```
|
||||
export module <module-name>.<sub_module-name>;
|
||||
import <module-name>.<sub_module-name>; // 可以在import前面添加export导出该分区接口
|
||||
```
|
||||
|
||||
上面的例子也可以用子模块来实现,我们将shape依旧作为主模块,两个子模块分别是circle与rectangle。
|
||||
|
||||
```cpp
|
||||
// shape.cppm
|
||||
export module shape;
|
||||
|
||||
export import shape.circle;
|
||||
export import shape.rectangle;
|
||||
|
||||
---------------------
|
||||
// rectangle.cppm
|
||||
module;
|
||||
#include <iostream>
|
||||
export module shape.rectangle;
|
||||
export void DrawRectangle() { std::cout << "draw rectangle" << std::endl; }
|
||||
|
||||
---------------------
|
||||
|
||||
// circle.cppm
|
||||
module;
|
||||
#include <iostream>
|
||||
export module shape.circle;
|
||||
export void DrawCircle() { std::cout << "draw circle" << std::endl; }
|
||||
```
|
||||
|
||||
可以看到在使用上模块分区用的是`:`,而子模块用的是`.`。
|
||||
|
||||
调用侧代码同模块分区。
|
||||
|
||||
不过它们在使用的时候有一些区别,例如:当子分区被引入时,使用其接口引发错误:internal compiler error: Segmentation fault: 11,而子模块是可以正常被引入使用。
|
||||
|
||||
```cpp
|
||||
// 引入子分区
|
||||
import shape:circle;
|
||||
|
||||
int main() {
|
||||
DrawCircle(); // error
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// 引入子模块
|
||||
import shape.circle;
|
||||
|
||||
int main() {
|
||||
DrawCircle(); // ok
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
对于子模块来说,在import时,不可以省略主模块名,上面在主分区中引入分区模块,我们可以使用`:circle`,这里不可以使用`.circle`。报错如下:
|
||||
|
||||
```cpp
|
||||
shape.cppm:3:8: error: 'import' does not name a type
|
||||
3 | export import .circle;
|
||||
```
|
||||
|
||||
## 4.接口与实现
|
||||
|
||||
通常在写代码时,我们会将代码拆分为"头文件"与"实现文件",对于模块来说,这一操作不再需要。但是仍旧可以遵循以前的编写风格。
|
||||
|
||||
例如:绘制一个shape。
|
||||
|
||||
- 定义模块shape.cppm
|
||||
|
||||
```cpp
|
||||
export module shape;
|
||||
|
||||
export class Shape {
|
||||
public:
|
||||
Shape();
|
||||
void Draw();
|
||||
};
|
||||
```
|
||||
|
||||
- 实现模块shape.cc
|
||||
|
||||
```cpp
|
||||
import shape;
|
||||
import <iostream>;
|
||||
|
||||
Shape::Shape() {}
|
||||
void Shape::Draw() { std::cout << "draw a shape" << std::endl; }
|
||||
```
|
||||
|
||||
跟平时使用`.h`与`.cpp`的分离模式基本类似。
|
||||
|
||||
> https://clang.llvm.org/docs/StandardCPlusPlusModules.html
|
||||
>
|
||||
> https://timsong-cpp.github.io/cppwp/n4861/module.import#7.sentence-2
|
||||
>
|
||||
> https://gcc.gnu.org/projects/cxx-status.html
|
||||
135
site_extras/modern-cpp-cpp20-cpp20-ranges.md
Normal file
135
site_extras/modern-cpp-cpp20-cpp20-ranges.md
Normal file
@@ -0,0 +1,135 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-ranges/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 Ranges 库
|
||||
|
||||
[TOC]
|
||||
|
||||
ranges是C++20的主要特性之一,其中"view"是比较重要的一部分。C++20之前,标准库的算法实现是基于迭代器来实现的,例如:std::sort。
|
||||
|
||||
```cpp
|
||||
std::sort(v.begin() + 2, v.end())
|
||||
```
|
||||
|
||||
迭代器 + 算法能够完成一些复杂的操作,例如:我想要倒这排序:
|
||||
|
||||
```cpp
|
||||
std::sort(v.rbegin(), v.rend())
|
||||
```
|
||||
|
||||
但是它也伴随着一些问题:
|
||||
|
||||
- 容易混用两个不兼容的迭代器。
|
||||
- 算法的组合能力太弱,需要存储一些中间变量
|
||||
|
||||
例如:现在有一个学生信息系统,我们想要计算**年龄在21-25区间且GPA >= 3.5,求取满足前面条件的学生总GPA**。C++17之前我们可以写出下面这样的伪代码:
|
||||
|
||||
```cpp
|
||||
std::vector<Student> students
|
||||
std::vector<Student> selected;
|
||||
std::copy_if(students.begin(), students.end(), std::back_inserter(selected),
|
||||
[](const Student& student) {
|
||||
return student.age >= 21 && student.age <= 25 && student.gpa >= 3.5;
|
||||
});
|
||||
|
||||
double s = std::accumulate(
|
||||
selected.begin(), selected.end(), 0.0,
|
||||
[](double sum, const Student& student) { return sum + student.gpa; });
|
||||
```
|
||||
|
||||
可以看到我们在过滤前面满足条件的学生信息时需要将其拷贝到selected,然后再对其求和。
|
||||
|
||||
C++20 引入了一种更为简洁、高效的写法,通过使用范围和管道操作符 `|` 连接多个操作,可以在不需要中间变量的情况下直接求和,例如:
|
||||
|
||||
```cpp
|
||||
double s = 0.0;
|
||||
for (const auto& student :
|
||||
students | std::views::filter([](const auto& s) {
|
||||
return s.age >= 21 && s.age <= 25 && s.gpa >= 3.5;
|
||||
}) | std::views::transform([](const auto& s) { return s.gpa; })) {
|
||||
s += student;
|
||||
}
|
||||
```
|
||||
|
||||
可以看到多个算法之间无缝衔接,减少了中间临时变量的内存分配,其可读性也大大增加,通过管道`|`将不同的操纵连接在一块。
|
||||
|
||||
接下来,让我们一起探讨C++20 ranges相关的内容。
|
||||
|
||||
## 1.基础概念
|
||||
|
||||
1.range
|
||||
|
||||
range 是一种表示一个序列的抽象概念。它可以是任何具有迭代器的容器或者是一个定义了 `begin()` 和 `end()` 函数的对象。如 `std::vector`、`std::list` 等都是范围的例子。对于数组,也可以视为范围。
|
||||
|
||||
2.view
|
||||
|
||||
view 是对 Range 的一种只读访问。它是一种惰性计算的方式,只有在需要的时候才会进行计算,这意味着它并不实际存储数据。例如: `std::views::filter` 和 `std::views::transform` 就是view的典型例子。它们允许我们对 range 进行筛选和转换,而不必实际创建新的容器。
|
||||
|
||||
3.algorithm
|
||||
|
||||
算法是对range或view进行操作的函数,例如:`std::sort`、`std::find` 等都是算法的例子。
|
||||
|
||||
4.`|`
|
||||
|
||||
管道操作符`|`,可以将视图与算法链接起来,将左侧的结果作为右侧的输入。它使得代码更为清晰、简洁。例如: `students | std::views::filter(...)` 将 `students` 范围传递给 `std::views::filter` 进行过滤操作,然后再将结果传递给后续的操作。
|
||||
|
||||
以上面的student计算为示例,在这个例子中我们使用了范围students通过`|`作为视图filter的输入,然后将结果作为视图transform的输入,最后返回一个范围,基于这个范围进行循环,通过累加算法求和得到结果。
|
||||
|
||||
```cpp
|
||||
double s = 0.0;
|
||||
for (const auto& student :
|
||||
students | std::views::filter([](const auto& s) {
|
||||
return s.age >= 21 && s.age <= 25 && s.gpa >= 3.5;
|
||||
}) | std::views::transform([](const auto& s) { return s.gpa; })) {
|
||||
s += student;
|
||||
}
|
||||
```
|
||||
|
||||
可以看到,使用range有如下好处:
|
||||
|
||||
- 提高代码可读性
|
||||
- 懒惰计算: Ranges 引入了视图(view)的概念,允许懒惰计算,即在需要时才计算结果。
|
||||
|
||||
例如:只有在`*v.begin()`时才会去计算。
|
||||
|
||||
```cpp
|
||||
auto v = std::views::reverse(vec);
|
||||
std::cout << *v.begin() << std::endl;
|
||||
```
|
||||
|
||||
- 减少错误: Ranges 的设计有助于减少一些传统迭代器操作中容易出现的错误,例如使用不兼容的迭代器。
|
||||
- 等等。
|
||||
|
||||
范围概念引入了不同的概念来描述不同类型的范围。这些概念有助于在泛型编程中更好地理解和限制范围的特性。以下是一些常用的范围概念:
|
||||
|
||||
> https://en.cppreference.com/w/cpp/ranges
|
||||
|
||||
| 概念 | 描述 | 容器举例 |
|
||||
| ---------------------------------- | --------------------------------- | ------------------------------------------------------------ |
|
||||
| `std::ranges::input_range` | 可以从头到尾至少迭代一次 | std::forward_list、std::list、std::duque、std::array、std::vector |
|
||||
| `std::ranges::forward_range` | 可以从头到尾迭代多次 | std::forward_list、std::list、std::duque、std::array、std::vector |
|
||||
| `std::ranges::bidirectional_range` | 迭代器也可以向后移动`--` | std::list、std::duque、std::array、std::vector |
|
||||
| `std::ranges::random_access_range` | 你可以在常数时间内跳转到元素 `[]` | std::duque、std::array、std::vector |
|
||||
| `std::ranges::contiguous_range` | 元素总是连续存储在内存中 | std::array、std::vector |
|
||||
|
||||
## 2.使用
|
||||
|
||||
使用这个特性比较简单,只需要引入头文件,使用接口即可。
|
||||
|
||||
例如:过滤一堆数字当中的偶数。
|
||||
|
||||
```cpp
|
||||
#include <ranges>
|
||||
auto evenNumbers = numbers | std::views::filter([](int x) { return x % 2 == 0; });
|
||||
```
|
||||
|
||||
编译:指定-std即可。
|
||||
|
||||
```cpp
|
||||
g++ -std=c++20 main.cc -o main
|
||||
```
|
||||
|
||||
编译器支持可以阅读下面清单:
|
||||
|
||||
> https://en.cppreference.com/w/cpp/compiler_support/20
|
||||
|
||||
gcc >=10,clang >=13(partial),>=15全面支持。
|
||||
171
site_extras/modern-cpp-cpp20-cpp20-span.md
Normal file
171
site_extras/modern-cpp-cpp20-cpp20-span.md
Normal file
@@ -0,0 +1,171 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/cpp20-span/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 std::span 设计与陷阱
|
||||
|
||||
[TOC]
|
||||
|
||||
## 0.初衷
|
||||
|
||||
在传统C/C++代码中,我们通常会使用一个指针+大小来访问数组,比如:
|
||||
|
||||
```cpp
|
||||
void print(int* arr, int sz) {
|
||||
for (int i = 0; i < sz; i++) {
|
||||
// todo
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
span可以简化这一操作,变为:
|
||||
|
||||
```cpp
|
||||
void print(std::span<int> arr) {
|
||||
for (auto x : arr) {
|
||||
// todo
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
那么究竟什么是span、它的使用场景以及陷阱有哪些?本节进行详细的探讨。
|
||||
|
||||
## 1. 何谓`span`?
|
||||
|
||||
在 C++20 中,`span` 是一个轻量级的、范围类型的容器,它提供了对**一段连续内存**的访问。`span` 作为一个视图(view),并不拥有其数据,而是对数据的一个简单引用,常用于替代传统的 C 风格数组或指针。它可以容纳任意类型的数组和标准容器,如 `std::vector`,并提供一种更安全、更现代的方式来处理这些数据。
|
||||
|
||||
其中几个关键点:
|
||||
|
||||
- 连续内存
|
||||
- 不拥有数据
|
||||
- 引用
|
||||
|
||||
`span` 的源码位于gcc的libstdc++-v3/include/std/span。
|
||||
|
||||
```cpp
|
||||
template <typename _Type, size_t _Extent = dynamic_extent>
|
||||
class span {};
|
||||
```
|
||||
|
||||
`span` 类型包含两个重要的参数:
|
||||
|
||||
- `_Type`:元素类型。
|
||||
- `Extent`:数组大小。如果为 `dynamic_extent`(默认值),表示视图的大小可以动态变化。
|
||||
|
||||
## 2. `span` 的动态与静态
|
||||
|
||||
`span` 有两种模式:静态和动态。
|
||||
|
||||
### 2.1 静态 `span`
|
||||
|
||||
静态 `span` 在编译时确定其大小,它的 `Extent` 是一个常量值。使用静态 `span` 时,我们需要在编译时知道数据的大小。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
int arr[5] = {1, 2, 3, 4, 5};
|
||||
std::span<int, 5> s(arr); // 静态 span,大小为 5
|
||||
```
|
||||
|
||||
静态 `span` 的大小在编译时固定,因此可以利用编译器进行一些优化,比如边界检查的省略。但由于 `Extent` 是常量,因此静态 `span` 不能在运行时修改大小。
|
||||
|
||||
### 2.2 动态 `span`
|
||||
|
||||
动态 `span` 的大小在运行时确定,`Extent` 默认为 `dynamic_extent`。这种类型的 `span` 不要求在编译时确定大小,它可以适应任意大小的数组或容器。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
int arr[5] = {1, 2, 3, 4, 5};
|
||||
std::span<int> s(arr); // 动态 span,大小在运行时确定
|
||||
```
|
||||
|
||||
动态 `span` 适用于那些无法在编译时确定大小的情况,它提供了更大的灵活性。
|
||||
|
||||
gcc源码里面实现比较简单,默认是一个非常大的整数(-1的无符号数),真正计算的时候是在构造的时候。
|
||||
|
||||
```cpp
|
||||
inline constexpr size_t dynamic_extent = static_cast<size_t>(-1);
|
||||
```
|
||||
|
||||
比如:这里会使用ranges::size设置内部大小,具体见下面代码。
|
||||
|
||||
```cpp
|
||||
std::vector<int> data{1, 2, 3};
|
||||
std::span<int> s(data);
|
||||
```
|
||||
|
||||
设置动态大小。
|
||||
|
||||
```cpp
|
||||
span(ranges::data(__range), ranges::size(__range))
|
||||
```
|
||||
|
||||
## 3. `subspan`
|
||||
|
||||
`span` 提供了一个非常有用的成员函数 `subspan`,它允许我们从一个现有的 `span` 中提取一个子视图,而无需复制数据。这非常适用于处理大数据集时,避免不必要的内存开销。
|
||||
|
||||
`subspan()` 方法有两个重载:
|
||||
|
||||
1. 一个接受 `__offset` 和 `__count` 作为参数,其中 `__offset` 是起始位置,`__count` 是子范围的大小(默认为 `dynamic_extent`,即到原 `span` 的末尾)。
|
||||
2. 另一个没有参数,基于模版实现。
|
||||
|
||||
```cpp
|
||||
constexpr auto
|
||||
subspan() const noexcept
|
||||
-> span<element_type, _S_subspan_extent<_Offset, _Count>()> {}
|
||||
|
||||
template<size_t _Offset, size_t _Count = dynamic_extent>
|
||||
[[nodiscard]]
|
||||
constexpr auto
|
||||
subspan() const noexcept
|
||||
-> span<element_type, _S_subspan_extent<_Offset, _Count>()> {}
|
||||
```
|
||||
|
||||
示例1:
|
||||
|
||||
```cpp
|
||||
std::span<int> s(arr);
|
||||
std::span<int> sub = s.subspan(1, 3);
|
||||
```
|
||||
|
||||
示例2:
|
||||
|
||||
```cpp
|
||||
std::span<int> s(arr);
|
||||
auto sub = s.subspan<2, 2>();
|
||||
```
|
||||
|
||||
## 4. 使用陷阱
|
||||
|
||||
虽然 `span` 是一个非常有用的工具,但在使用时也有一些常见的陷阱需要注意:
|
||||
|
||||
### 4.1 不要让 `span` 引用已经释放的内存
|
||||
|
||||
`span` 本身并不拥有数据,它只是对数据的引用。因此,如果 `span` 引用的内存被释放(例如原数组被销毁或超出作用域),那么访问该 `span` 将导致未定义行为。
|
||||
|
||||
例如:
|
||||
|
||||
```cpp
|
||||
std::span<int> create_span() {
|
||||
int arr[5] = {1, 2, 3, 4, 5};
|
||||
return std::span<int>(arr, 5);
|
||||
}
|
||||
|
||||
// 错误:返回的 span 引用了栈上临时变量,函数返回后 arr 被销毁
|
||||
auto s = create_span();
|
||||
```
|
||||
|
||||
为了解决这个问题,应确保 `span` 引用的数据在其生命周期内有效。可以考虑将数据持有在动态分配的内存中,或者确保数据的生命周期和 `span` 的生命周期一致。
|
||||
|
||||
### 4.2 改变底层数组大小时的问题
|
||||
|
||||
`span` 对底层数据的引用是直接的,而不是复制。当底层的数据发生变化时,`span` 本身并不会感知这些变化。因此,改变底层数组或容器的大小(例如通过重新分配内存)时,原来的 `span` 可能会变得无效。
|
||||
|
||||
```cpp
|
||||
std::vector<int> vec = {1, 2, 3, 4, 5};
|
||||
std::span<int> s(vec); // s 引用 vec 的数据
|
||||
// 改变底层容器的大小
|
||||
vec.push_back(6); // vec 大小变为 6
|
||||
|
||||
// 这里 s 仍然引用 vec 的数据,但 vec 可能已经重新分配了内存
|
||||
// 这可能导致 s 引用失效或未定义行为
|
||||
```
|
||||
38
site_extras/modern-cpp-cpp20-embrace-cpp20.md
Normal file
38
site_extras/modern-cpp-cpp20-embrace-cpp20.md
Normal file
@@ -0,0 +1,38 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/embrace-cpp20/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 新特性导读
|
||||
|
||||
在之前的文章中零零散散的写了几篇C++20的重要特性,例如:
|
||||
|
||||
|
||||
|
||||
接下来本篇将会简单的列一些比较重要的特性供大家参考,陈述一下为什么大家需要学习C++20,它能够给大家代码什么样的好处。
|
||||
|
||||
**C++20**是继C++17之后的C++编程语言的ISO/IEC标准修订版的名称。C++ 是一种通用高性能编程语言,被广泛用于各种应用领域,包括操作系统、浏览器以及许多其他类型的软件。
|
||||
|
||||
C++20 引入了许多新特性和改进,旨在使 C++ 更具表现力、高效且易于使用。C++20 的一些最重要的特性包括:
|
||||
|
||||
- **概念(Concepts)**:使模板编程变得更加直观、可靠和易于使用。通过使用概念,我们可以编写更具表现力和可读性的代码,同时在编译时获得更好的错误检查和更准确的自动推导。
|
||||
- **协程(Coroutines)**:一种以同步风格编写异步代码的方式,使得编写可以暂停和恢复而不阻塞整个程序的代码更加容易。
|
||||
- **模块(Modules)**:一种组织和重用代码的新方式,简化了构建和分发大型软件项目的过程。
|
||||
- **Ranges(范围)**:引入了范围库(算法和迭代器库的扩展和泛化),提供了一种更直观、简洁和功能丰富的方式来处理和操作集合数据。
|
||||
- **太空船操作符(Spaceship operator)**:一种用于比较对象三路排序的新操作符,使得编写比较和排序复杂数据结构的代码更加容易。
|
||||
- **constexpr lambdas**:将 lambda 用作 constexpr 函数的能力,允许在更多上下文中使用 lambda 表达式,包括在常量表达式和模板参数中使用。
|
||||
- **指定初始化器(Designated initializers)**:用于初始化结构体和数组的更具表现力的语法,使得更容易指定结构体或数组的各个成员的值。
|
||||
|
||||
C++20 还包括许多其他改进和变化,如额外的库设施、性能提升以及对现代硬件和平台的更好支持。总的来说,C++20 代表了 C++ 语言的一大步前进,并预计将对未来 C++ 的使用和开发产生重要影响。
|
||||
|
||||
## C++20 的好处
|
||||
|
||||
C++20 引入了许多新特性和改进,旨在提高 C++ 代码的生产力和表现力。C++20 的一些好处包括:
|
||||
|
||||
- **性能提升:** C++20 包括许多旨在提高 C++ 代码性能的更改和改进。例如,C++20 引入了 `std::format` 库,为字符串格式化提供了一个高性能的替代方案,用于替代 `printf` 和 `sprintf`。C++20 还包括对 `std::variant` 和 `std::optional` 类型的改进,可以帮助减少在某些情况下使用这些类型的开销。此外,C++20 引入了 `std::bit_cast` 函数,提供了一种安全有效地执行类型转换的方式。
|
||||
- **对现代硬件和平台的更好支持:** C++20 包括许多旨在使编写针对现代硬件和平台进行优化的代码更加容易的更改和改进。例如,C++20 引入了 `std::atomic_ref` 类型,提供了一种在非原子对象上执行原子操作的方法。C++20 还包括对 `std::endian` 类型的支持,允许你编写跨不同字节顺序体系结构的可移植代码。此外,C++20 引入了 `std::span` 类型,提供了一种在内存中表示连续对象序列的方法,并且可以用于编写针对缓存友好访问模式进行优化的代码。
|
||||
- **模块化编程:** C++20 引入了模块化编程的支持,这是一种新的组织代码的方式,允许开发人员将代码分割成逻辑上独立的模块。。
|
||||
- 等等
|
||||
|
||||
## 小结
|
||||
|
||||
总之,C++20 是 C++ 编程语言的一个重要新版本,引入了许多新特性和改进,旨在提高 C++ 代码的生产力和表现力。C++20 的一些关键特性包括概念、协程、模块、范围、太空船操作符、constexpr lambdas、指定初始化器和类的默认成员初始化器。这些特性可以帮助提高 C++ 代码的性能、灵活性和模块性,并且可以使得更容易编写针对现代硬件和平台进行优化的代码。
|
||||
|
||||
如果你是 C++ 程序员,我们鼓励你了解更多关于 C++20 的信息,并开始在自己的代码中使用它的新特性。C++20 是一种强大且多功能的语言,可以帮助你编写高效、表现力强且易于维护的代码。通过利用 C++20 引入的新特性和改进,你可以提高生产力,并编写更适合项目需求的代码。
|
||||
76
site_extras/modern-cpp-cpp20-likely-unlikely-attributes.md
Normal file
76
site_extras/modern-cpp-cpp20-likely-unlikely-attributes.md
Normal file
@@ -0,0 +1,76 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/likely-unlikely-attributes/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 [[likely]] 与 [[unlikely]]
|
||||
|
||||
C++20 引入了 `[[likely]]` 和 `[[unlikely]]` 这两个可能性属性,它们会给编译器优化提示,表示对应代码路径可能/不可能被执行。
|
||||
|
||||
乍一看,这似乎是一组很不错的属性,通过编译器优化,从而提高性能。但是事实并不是如此。
|
||||
|
||||
在C++ 标准草案中明确提到:Excessive usage of either of these attributes is liable to result in performance degradation.
|
||||
|
||||
即:过度使用任何一个属性都可能导致性能下降。
|
||||
|
||||
> https://eel.is/c++draft/dcl.attr.likelihood#note-2
|
||||
|
||||
那么在什么情况下会比较有用,什么情况下又不需要呢?
|
||||
|
||||
本文谈谈自己的观点。
|
||||
|
||||
## 1.原则
|
||||
|
||||
使用时应该遵循以下原则:
|
||||
|
||||
1. **谨慎使用**:仅在你确定某个分支或路径在运行时极其可能或不可能时使用这些属性。
|
||||
|
||||
例如:下面这个判断一个value是不是大于0,如果输入的数据无法保证value很大概率/一定是大于0的,那么下面这个优化没有任何意义。
|
||||
|
||||
```cpp
|
||||
if (value > 0) [[likely]] {
|
||||
std::cout << "Value is positive: " << value << std::endl;
|
||||
} else [[unlikely]] {
|
||||
std::cout << "Value is non-positive: " << value << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
例如:标准库中使用unlikely的示例。`_Variant_storage`结构体中的成员函数使用了这个属性,无效的概率非常低,所以可能使用unlikely去标记。
|
||||
|
||||
```cpp
|
||||
constexpr void
|
||||
_M_reset()
|
||||
{
|
||||
if (!_M_valid()) [[unlikely]]
|
||||
return;
|
||||
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
2. **标记主导路径**:只在主导执行路径上使用属性,而不是在所有可能路径上。
|
||||
|
||||
例如:下面一个if判断标记了两个等效的likely,那么这个意义不大。
|
||||
|
||||
```cpp
|
||||
if (value > 10) [[likely]] {
|
||||
// 主导路径:值大于 10
|
||||
std::cout << "Value is greater than 10: " << value << std::endl;
|
||||
} else if (value > 5) [[likely]] {
|
||||
// 次主导路径:值大于 5 且小于等于 10
|
||||
std::cout << "Value is greater than 5 but less than or equal to 10: " << value << std::endl;
|
||||
} else [[unlikely]] {
|
||||
// 较少出现的路径:值小于等于 5
|
||||
std::cout << "Value is 5 or less: " << value << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
## 2.示例
|
||||
|
||||
最后举一个比较常见的例子,那便是vector的at,我们知道它会判断是否超过vector的size,这种概率比较低,所以我们可以使用unlikely,例如:
|
||||
|
||||
```cpp
|
||||
int& at(std::vector<int>& vec, std::size_t i) {
|
||||
if (i >= vec.size()) [[unlikely]] {
|
||||
throw std::out_of_range("Out of bounds access");
|
||||
}
|
||||
return vec[i];
|
||||
}
|
||||
```
|
||||
60
site_extras/modern-cpp-cpp20-no-unique-address.md
Normal file
60
site_extras/modern-cpp-cpp20-no-unique-address.md
Normal file
@@ -0,0 +1,60 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/no-unique-address/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 [[no_unique_address]]
|
||||
|
||||
## C++那些事之内存优化
|
||||
|
||||
通常程序运行时内存是一个比较大的问题,如何减少内存占用和提升访问速度是至关重要。为了解决这些问题,C++20 引入了 `no_unique_address` 特性,并结合空基类优化(EBO, Empty Base Optimization),为开发者提供了一种有效的方式来优化内存布局。
|
||||
|
||||
#### 1. 空基类优化(EBO)
|
||||
|
||||
EBO 是指对于空基类(即没有数据成员的类)在派生类中的存在不会占用额外的内存。C++ 编译器会将这些空基类的实例合并,避免不必要的内存开销。这在设计复杂的类层次结构时尤其有用,可以有效减少对象的大小。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
class Empty {};
|
||||
|
||||
class Derived : public Empty {
|
||||
int value;
|
||||
|
||||
public:
|
||||
Derived(int v) : value(v) {}
|
||||
};
|
||||
|
||||
class Test {
|
||||
int value;
|
||||
|
||||
public:
|
||||
Test(int v) : value(v) {}
|
||||
Empty e;
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::cout << sizeof(Derived) << std::endl;
|
||||
std::cout << sizeof(Test) << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
在上面的代码中,`Derived` 类在内存中只占用 `int` 的大小,而不是 `int` 加上 `Empty` 的大小。这是因为编译器利用了 EBO 的特性。
|
||||
|
||||
**那么你猜猜上面的输出是多少呢?**
|
||||
|
||||
#### 2. `no_unique_address` 特性
|
||||
|
||||
C++20 引入了 `no_unique_address` 特性,它允许我们显式标记某些类成员,使其在内存中不会占用额外空间。特别适合<0字节对象>,例如:
|
||||
|
||||
unique_ptr中当Deleter是空结构体/类,此时得到的sizeof是16,C++20之后便可以不占子节,整个sizeof为8。
|
||||
|
||||
```cpp
|
||||
template<class T, class Deleter>
|
||||
class unique_ptr {
|
||||
T* pointer = nullptr;
|
||||
[[no_unique_address]] Deleter deleter;
|
||||
|
||||
public:
|
||||
// 其他成员函数...
|
||||
};
|
||||
```
|
||||
|
||||
> 本节完
|
||||
99
site_extras/modern-cpp-cpp20-spaceship-operator.md
Normal file
99
site_extras/modern-cpp-cpp20-spaceship-operator.md
Normal file
@@ -0,0 +1,99 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/modern-cpp/cpp20/spaceship-operator/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++20 三路比较运算符 <=>
|
||||
|
||||
## 三种排序
|
||||
|
||||
三向比较运算符`<=>`又称为宇宙飞船运算符,返回值有三种排序,下面从gcc源码角度来深入聊一下。
|
||||
|
||||
注:懒人版,本节示例已更新星球。
|
||||
|
||||
用法:`<=>`
|
||||
|
||||
```cpp
|
||||
#include <compare>
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
auto c1 = 1.1 <=> 2.2;
|
||||
auto c2 = -1 <=> 1;
|
||||
std::cout << typeid(c1).name() << std::endl;
|
||||
std::cout << typeid(c2).name() << std::endl;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```cpp
|
||||
St16partial_ordering
|
||||
St15strong_ordering
|
||||
```
|
||||
|
||||
1. `1.1 <=> 2.2`:这是对两个浮点数进行比较。对于浮点数,标准库返回的是`std::partial_ordering`,因为浮点数有NaN值的存在,这使得它们之间的比较不是严格的全序。`std::partial_ordering`允许结果是`<`、`>`、`==`或者`unordered`。
|
||||
|
||||
我们可以使用gcc代码静态变量来查看partial_ordering到底是小于、大于、等于、无序:
|
||||
|
||||
```cpp
|
||||
static const partial_ordering less;
|
||||
static const partial_ordering equivalent;
|
||||
static const partial_ordering greater;
|
||||
static const partial_ordering unordered;
|
||||
```
|
||||
|
||||
如果我们强制转换便会报错:
|
||||
|
||||
```cpp
|
||||
comp.cc:6:36: error: conversion from 'std::partial_ordering' to non-scalar type 'std::strong_ordering' requested
|
||||
6 | std::strong_ordering c1 = 1.1 <=> 2.2;
|
||||
```
|
||||
|
||||
2. `-1 <=> 1`:这是对两个整数进行比较。对于整数,标准库返回的是`std::strong_ordering`,因为整数的比较是严格的全序关系,没有不确定的情况。`std::strong_ordering`只会返回`<`、`>`或`==`。
|
||||
|
||||
同理,可以使用下面4个静态成员。
|
||||
|
||||
```cpp
|
||||
static const strong_ordering less;
|
||||
static const strong_ordering equal;
|
||||
static const strong_ordering equivalent;
|
||||
static const strong_ordering greater;
|
||||
```
|
||||
|
||||
因此,`c1`的类型是`std::partial_ordering`,而`c2`的类型是`std::strong_ordering`,这也解释了为什么输出的类型不一样。
|
||||
|
||||
除了partial_ordering、strong_ordering之外,`<=>`还可能返回weak_ordering,静态成员为:
|
||||
|
||||
```cpp
|
||||
static const weak_ordering less;
|
||||
static const weak_ordering equivalent;
|
||||
static const weak_ordering greater;
|
||||
```
|
||||
|
||||
## equal与equivalent
|
||||
|
||||
在上面的三种ording可以看到对于等于出现了两个:equal与equivalent,这两者有什么区别呢?
|
||||
|
||||
这里直接看cppreference,两者之间没有区别。然而,std::strong_ordering 是唯一定义相等的类别。所有其他类别仅定义等价。也正好验证了上面的静态成员,对于string_ordering有两个,其他的只有equivalent。
|
||||
|
||||
如果比较在被比较的项目之间产生**强排序**,则等价和相等是相同的。之所以有两个词来表示它,是因为这对于其他类型的排序是不一样的。**弱**和**部分**根本**没有相等性**;它们**只提供等价性**。
|
||||
|
||||
等价意味着两个对象可以比较相等。相等意味着更强的东西;如果它们比较相等,则可以在任何 const 用法中用一个替换另一个:只要 a == b 为真,f(a) == f(b) 的属性就为真,其中 f 表示仅读取可通过参数的公共 const 成员访问的比较突出状态的函数。如果类型的比较允许相等(这是强排序的要求),那么它也允许等价。因此,对于强排序比较,它们是相同的。
|
||||
|
||||
> https://en.cppreference.com/w/cpp/utility/compare/strong_ordering
|
||||
|
||||
## 为什么使用三向比较运算符?
|
||||
|
||||
三向比较运算符(<=>)使得在一次操作中就能够确定两个值的排序关系,而传统的比较运算符则需要多次比较。
|
||||
|
||||
**传统比较运算符的限制:**
|
||||
|
||||
- 如果 `a == b` 为假,你无法知道 `a < b` 还是 `a > b`。
|
||||
- 如果 `a != b` 为真,你无法知道 `a < b` 还是 `a > b`。
|
||||
- 如果 `a < b` 为假,你无法知道 `a == b` 还是 `a > b`。
|
||||
- 如果 `a > b` 为假,你无法知道 `a == b` 还是 `a < b`。
|
||||
- 如果 `a <= b` 为真,你无法知道 `a == b` 还是 `a < b`。
|
||||
- 如果 `a >= b` 为真,你无法知道 `a == b` 还是 `a > b`。
|
||||
|
||||
这些限制表明,传统的比较运算符不能一次性确定两个值的完全关系,而是需要多次比较来获得完整的结果。
|
||||
|
||||
> 本节完
|
||||
29
site_extras/resources-bilibili-cpp-tutorials.md
Normal file
29
site_extras/resources-bilibili-cpp-tutorials.md
Normal file
@@ -0,0 +1,29 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/resources/bilibili-cpp-tutorials/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# B 站 C++ 视频教程
|
||||
|
||||
## 1. 视频地址
|
||||
|
||||
相关视频在 B 站更新,B 站搜索用户:**未来的光城**,或点击下方分集链接。
|
||||
|
||||
## 2. 视频内容
|
||||
|
||||
### 2.1 环境那些事
|
||||
|
||||
- [第一期:Step By Step 上手编译本项目](https://www.bilibili.com/video/BV1Rv4y1H7LB/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第二期:免开发环境 docker](https://www.bilibili.com/video/BV1oz4y1a7Pu/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
### 2.2 手把手共读 STL
|
||||
|
||||
- [第三期:手把手共读 HashTable,彻底搞懂 C++ STL](https://www.bilibili.com/video/BV1o8411U7vy/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第四期:手把手共读 STL 之 enable_shared_from_this](https://www.bilibili.com/video/BV1du4y1w7Mg/?spm_id_from=333.788&vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第五期:手把手共读 STL 之线程,从 C++11 thread 到 C++20 jthread](https://www.bilibili.com/video/BV1DH4y1g7gS/?vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第六期:手把手共读 STL 之 condition_variable、condition_variable_any](https://www.bilibili.com/video/BV13b421b7Am/?spm_id_from=333.999.0.0&vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第七期:手把手共读 STL 之 Mutex](https://www.bilibili.com/video/BV1xm42157pq/?spm_id_from=333.999.0.0&vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
|
||||
- [第八期:手把手共读 STL 之 RAII Lock](https://www.bilibili.com/video/BV1Ls421g7iq/?spm_id_from=333.788&vd_source=bb6532dcd5b1d6b26125da900adb618e)
|
||||
21
site_extras/resources-cpp-learning-resources.md
Normal file
21
site_extras/resources-cpp-learning-resources.md
Normal file
@@ -0,0 +1,21 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/resources/cpp-learning-resources/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 学习资源与书单
|
||||
|
||||
## 资料
|
||||
|
||||
[*Modern C++ Design*](https://book.douban.com/subject/1755195/)
|
||||
|
||||
[Introduction to C++ Metaprogramming](http://odinthenerd.blogspot.com/2014/07/introduction-to-c-metaprogramming-part-1.html)
|
||||
|
||||
[CppCon 2017: Ben Deane & Jason Turner “constexpr ALL the Things!”](https://www.youtube.com/watch?v=PJwd4JLYJJY)
|
||||
|
||||
[CppCon 2020 - Structure and Interpretation of Computer Programs: SICP - Conor Hoekstra](https://www.youtube.com/watch?v=7oV7hiAsVTI)
|
||||
|
||||
[C++ Template: A Quick UpToDate Look(C++11/14/17/20)](http://www.vishalchovatiya.com/c-template-a-quick-uptodate-look/)
|
||||
|
||||
[*Category Theory for Programmers*](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)
|
||||
|
||||
[*Structure and Interpretation of Computer Programs - MIT*](https://web.mit.edu/alexmv/6.037/sicp.pdf)
|
||||
|
||||
[*Learn You a Haskell*](http://learnyouahaskell.com/)
|
||||
7
site_extras/resources-feishu-cpp-knowledge-base.md
Normal file
7
site_extras/resources-feishu-cpp-knowledge-base.md
Normal file
@@ -0,0 +1,7 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/resources/feishu-cpp-knowledge-base/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# C++ 学习知识库
|
||||
|
||||
- [互联网大厂面试实录](https://hmpy6adnp5.feishu.cn/docx/OitBdRB4KozIhTxQt7Ec7iFDnkc)
|
||||
|
||||
- [拿下 offer 之必备面经](https://hmpy6adnp5.feishu.cn/docx/B1aCdVTUgoyJGYxtWV7cdvgRnxv)
|
||||
124
site_extras/stl-source-analysis-cpp-string-deep-dive.md
Normal file
124
site_extras/stl-source-analysis-cpp-string-deep-dive.md
Normal file
@@ -0,0 +1,124 @@
|
||||
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/stl-source-analysis/cpp-string-deep-dive/) 的文章,由站点同步脚本导出。
|
||||
|
||||
# STL string 深析
|
||||
|
||||
当我们使用C++时,<string>库的基础知识比较熟悉,尤其是在C++中创建字符串时使用的std::string。这无疑是对旧的C风格“字符串”(使用以空字符结尾的字符数组)的一种改进。然而,C++标准库在C++17和C++20中引入了更有用的组件,可以帮助你编写更高效的代码。
|
||||
|
||||
在<string>头文件中,std::basic_string类是一个模板类,为各种字符串类型提供了特化,包括常见字符串的std::string(即std::basic_string<char>)和宽字符串的std::wstring(即std::basic_string<wchar_t>)。
|
||||
|
||||
还有一些固定宽度的特定字符串,比如std::u32string(即std::basic_string<char32_t>)和std::u16string(即std::basic_string<char16_t>)。
|
||||
|
||||
在C++20中,引入了char8_t,这也带来了std::u8string(即std::basic_string<char8_t>)。我不知道为什么要等到C++20才引入char8_t,那么提个问题**char16_t和char32_t在哪个标准存在呢?留言区见**
|
||||
|
||||
### C++11
|
||||
|
||||
在C++11标准下,字符串处理主要依赖于`std::string`类,这是一个动态分配内存的字符串类。此外,引入了新的固定宽度字符串类型,如`std::u32string`和`std::u16string`,为处理Unicode字符提供了更好的支持。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main() {
|
||||
// 使用std::string
|
||||
std::string str = "Hello, C++11!";
|
||||
|
||||
// 使用std::u32string和std::u16string
|
||||
std::u32string u32str = U"Hello, Unicode!";
|
||||
std::u16string u16str = u"Hello, Unicode!";
|
||||
|
||||
std::cout << str << std::endl;
|
||||
std::wcout << u32str << std::endl;
|
||||
std::wcout << u16str << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### C++17
|
||||
|
||||
在C++17中,引入了<string_view>头文件,提供了一种轻量级的只读替代方案,用于使用<string>头文件中的字符串类型。这些字符串视图类似于先前描述的字符串。例如,std::u32string的<string_view>等价物是std::u32string_view(即std::basic_string_view<char32_t>)。
|
||||
|
||||
这在需要读取字符串但不需要修改它的函数中特别有用。与**为函数创建字符串副本**不同,我们可以简单地查看现有字符串!此外,<string_view>非常灵活,不仅可以将C++样式的字符串转换为字符串视图,甚至可以将C样式的字符串转换为字符串视图。以下是演示std::string_view简单用法的示例:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
void printString(std::string_view str) {
|
||||
std::cout << str << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::string_view strv{"strv"}; // C++ string_view
|
||||
printString(strv);
|
||||
|
||||
std::string str{"str"}; // C++ string
|
||||
printString(str);
|
||||
|
||||
char cstr[] = "cstr"; // C-style string
|
||||
printString(cstr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```
|
||||
strv
|
||||
str
|
||||
cstr
|
||||
```
|
||||
|
||||
在这个例子中,printString函数以std::string_view作为参数,这使得这个函数非常轻量级和灵活,因为没有制作任何字符串的副本,这个函数可以通过传递C和C++样式的字符串以各种方式使用。
|
||||
|
||||
### C++20
|
||||
|
||||
在C++20中,引入了一些新的有用成员函数,包括starts_with(…)和ends_with(…)。正如名称所示,这些函数确定一个字符串(或字符串视图)是否以某个字符或某个std::string_view开头/结尾。以下是一个简单的例子:
|
||||
|
||||
```cpp
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
int main() {
|
||||
const std::string str{"Hello World!"};
|
||||
|
||||
assert(str.starts_with('H'));
|
||||
assert(str.ends_with('!'));
|
||||
|
||||
assert(str.starts_with("Hello")); // 隐式转换为std::string_view
|
||||
assert(str.ends_with("World!")); // 隐式转换为std::string_view
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### C++23
|
||||
|
||||
C++23中引入了`contains`,用于检查字符串是否包含指定的子字符串。
|
||||
|
||||
```cpp
|
||||
// 这是一个假设的C++23示例,实际上并不可用
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main() {
|
||||
std::string str = "C++23 introduces contains function.";
|
||||
|
||||
if (str.contains("introduces")) {
|
||||
std::cout << "The string contains 'introduces'." << std::endl;
|
||||
} else {
|
||||
std::cout << "The string does not contain 'introduces'." << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
> https://en.cppreference.com/w/cpp/string/basic_string/contains
|
||||
|
||||
### 结论
|
||||
|
||||
在处理新的C++代码中的字符串时,应考虑使代码尽可能灵活和内存高效。使用<string_view>可以极大地帮助这些努力。此外,考虑使用最新的字符串成员函数,如starts_with和ends_with,以获得可读且易于实现的字符串解析代码。而C++23使得contains计算更加简单,越来越现代化了。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user