Skip to content

Commit

Permalink
update 2024年09月 1日 18:49:16
Browse files Browse the repository at this point in the history
  • Loading branch information
vanJker committed Sep 1, 2024
1 parent ff69d2f commit 2fff689
Show file tree
Hide file tree
Showing 15 changed files with 785 additions and 142 deletions.
171 changes: 171 additions & 0 deletions content/posts/cpp/modern-cpp.md
Original file line number Diff line number Diff line change
Expand Up @@ -2483,6 +2483,173 @@ int main()

如果是生产环境则使用智能指针,如果是学习则使用原始指针。当然,如果你需要定制的话,也可以使用自己写的智能指针。

#### Track Memory Allocations

- cppreference: [operator new, operator new[]](https://en.cppreference.com/w/cpp/memory/new/operator_new)
- cppreference: [operator delete, operator delete[]](https://en.cppreference.com/w/cpp/memory/new/operator_delete)

```c++
#include <iostream>
#include <string>
#include <memory>

void* operator new(size_t size)
{
std::cout << "Allocating " << size << " bytes\n";

return malloc(size);
}

void operator delete(void* addr, size_t size)
{
std::cout << "Freeing " << size << " bytes\n";

free(addr);
}

struct Object
{
int x, y, z;
};

int main()
{
std::string str = "Hello";

{
std::unique_ptr<Object> unique = std::make_unique<Object>();
}
}
```

通过重载 `new``delete` 运算符,以及在重载的 `new``delete` 运算符方法中进行断点,配合调试器的 **调用堆栈** 功能可以追踪内存分配和释放操作的来源。

在此基础上可以构建一个简单快速的 **内存分配跟踪器** 工具:

```c++
#include <iostream>
#include <string>
#include <memory>

struct AllocationMetrics
{
size_t TotalAllocated = 0;
size_t TotalFreed = 0;

size_t CurrentUsage() { return TotalAllocated - TotalFreed; }

static AllocationMetrics& Get()
{
static AllocationMetrics s_AllocationMetrics;
return s_AllocationMetrics;
}

static void PrintMemoryUsage()
{
std::cout << "Memory Usage: " << Get().CurrentUsage() << " bytes\n";
}
};

void* operator new(size_t size)
{
AllocationMetrics::Get().TotalAllocated += size;

return malloc(size);
}

void operator delete(void* addr, size_t size)
{
AllocationMetrics::Get().TotalFreed += size;

free(addr);
}

struct Object
{
int x, y, z;
};

int main()
{
AllocationMetrics::PrintMemoryUsage();
std::string str = "Hello";
AllocationMetrics::PrintMemoryUsage();
{
std::unique_ptr<Object> unique = std::make_unique<Object>();
AllocationMetrics::PrintMemoryUsage();
}
AllocationMetrics::PrintMemoryUsage();
}
```

### lvalue and rvalue

- cppreference: [Value categories](https://en.cppreference.com/w/cpp/language/value_category)

lvalue 是 locator value,即可以被 locate 的 value,lvalue reference 就是对 lvalue 的引用。rvalue 为除了 lvalue 之外的 value,可以理解为临时字面值 (未被存储) 和亡值 (已被存储但地址未知,或者知道地址也没用,因为它很快就被销毁了),它们都无法被 located。

一般来说不能将 rvalue 传递给 lvalue reference (因为 reference 需要以可以被 located 为前提):

```c++
int& a = 10; // error
```

但可以将 rvalue 传递给 `const` 修饰的 lvalue reference:

```c++
const int& a = 10; // pass
// which is actually implemented by copmpiler
int temp = 10;
const int& a = temp;
```

所以函数参数常用 `const` 来修饰 reference,这样可以同时接受 lvalue 和 rvalue:

```c++
void PrintName(const std::string& name)
{
std::cout << name << std::endl;
}

int main()
{
std::string firstName = "Hello";
std::string lastName = "World";

std::string name = firstName + lastName;

PrintName(firstName);
PrintName(firstName + lastName);
}
```
但有时我们需要限制函数参数只接收 rvalue 而不接受 lvalue,此时就是 rvalue reference 大展身手的时机了。rvalue reference 使用 `&&` 来表示,其只能接收 rvalue 而不能接受 lvaue。将上面的例子改写为只接受 ravlue:
```c++
void PrintName(std::string& name) // only accept lvalue reference
{
std::cout << "[lvalue] " << name << std::endl;
}
void PrintName(std::string&& name) // only accept rvalue reference
{
std::cout << "[ravlue] " << name << std::endl;
}
int main()
{
std::string firstName = "Hello";
std::string lastName = "World";
std::string name = firstName + lastName;
PrintName(firstName); // [lvalue] Hello
PrintName(firstName + lastName); // [rvalue] HelloWorld
}
```

rvalue reference 对于优化比较重要,因为和 lvalue reference 不同,我们无需担心传入的 value 的生命周期问题,无需加入一些必要的生命周期检查,这样效率会很高。rvalue reference 常用于配合 move 移动语义来使用。

## Concurrency

### Threads
Expand Down Expand Up @@ -3080,6 +3247,10 @@ int main()
}
```

### Continuous Integration (CI)

- [Jenkins](https://www.jenkins.io/): Build great things at any scale

### Coding Style

个人偏好如下:
Expand Down
1 change: 1 addition & 0 deletions docs/css/c73f0d.min.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#id-31{background-color:green}#id-32{background-color:green}
2 changes: 1 addition & 1 deletion docs/index.json

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions docs/page/4/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@
</a><a href="/index.xml" title="RSS"target="_blank" rel="external nofollow noopener noreferrer me"><i class="fa-solid fa-rss fa-fw" aria-hidden="true"></i>
</a></div></div>
<article class="single summary" itemscope itemtype="http://schema.org/Article"><h2 class="single-title" itemprop="name headline"><span title="转载" class="icon-repost"><i class="fa-solid fa-share fa-fw" aria-hidden="true"></i></span><a href="/posts/csapp-ch2/">CS:APP 第 2 章重点提示和练习</a>
</h2><div class="post-meta"><span class="post-author"><span class="author"><i class="fa-solid fa-user-circle" aria-hidden="true"></i>
</span></span>&nbsp;<span class="post-publish" title='2024-04-19 15:33:40'>发布于 <time datetime="2024-04-19">2024-04-19</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/csapp/" class="post-category" title="分类 - CSAPP"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> CSAPP</a>&ensp;<a href="/categories/linux-kernel-internals/" class="post-category" title="分类 - Linux Kernel Internals"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Linux Kernel Internals</a></span></div><div class="content"><blockquote>
</h2><div class="post-meta"><span class="post-author"><a href="https://github.com/ccrysisa" title="作者"target="_blank" rel="external nofollow noopener noreferrer author" class="author"><img loading="lazy" src="https://avatars.githubusercontent.com/u/133117003?s=400&amp;v=4" alt="ccrysisa" data-title="ccrysisa" class="avatar" style="background: url(/images/loading.min.svg) no-repeat center;" onload="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}this.dataset.lazyloaded='';" onerror="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}"/>&nbsp;ccrysisa</a></span>&nbsp;<span class="post-publish" title='2024-04-19 15:33:40'>发布于 <time datetime="2024-04-19">2024-04-19</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/csapp/" class="post-category" title="分类 - CSAPP"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> CSAPP</a>&ensp;<a href="/categories/linux-kernel-internals/" class="post-category" title="分类 - Linux Kernel Internals"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Linux Kernel Internals</a></span></div><div class="content"><blockquote>
<p>千万不要小看数值系统,史上不少有名的 <a href="https://hackmd.io/@sysprog/software-failure"target="_blank" rel="external nofollow noopener noreferrer">软体缺失案例</a> 就因为开发者未能充分掌握相关议题,而导致莫大的伤害与损失。</p>
</blockquote></div><div class="post-footer">
<a href="/posts/csapp-ch2/">阅读全文</a><div class="post-tags"><i class="fa-solid fa-tags fa-fw me-1" aria-hidden="true"></i><a href='/tags/sysprog/' class="post-tag">Sysprog</a><a href='/tags/csapp/' class="post-tag">CSAPP</a></div></div>
Expand Down
6 changes: 2 additions & 4 deletions docs/page/5/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@
<a href="/posts/ics/">阅读全文</a><div class="post-tags"><i class="fa-solid fa-tags fa-fw me-1" aria-hidden="true"></i><a href='/tags/linux/' class="post-tag">Linux</a></div></div>
</article>
<article class="single summary" itemscope itemtype="http://schema.org/Article"><h2 class="single-title" itemprop="name headline"><span title="转载" class="icon-repost"><i class="fa-solid fa-share fa-fw" aria-hidden="true"></i></span><a href="/posts/english/">English Everyday</a>
</h2><div class="post-meta"><span class="post-author"><span class="author"><i class="fa-solid fa-user-circle" aria-hidden="true"></i>
</span></span>&nbsp;<span class="post-publish" title='2024-03-30 12:17:31'>发布于 <time datetime="2024-03-30">2024-03-30</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/draft/" class="post-category" title="分类 - Draft"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Draft</a></span></div><div class="content"><p>This post is used to record the process of my English learning.</p></div><div class="post-footer">
</h2><div class="post-meta"><span class="post-author"><a href="https://github.com/vanJker" title="作者"target="_blank" rel="external nofollow noopener noreferrer author" class="author"><img loading="lazy" src="https://avatars.githubusercontent.com/u/88960102?s=96&amp;v=4" alt="vanJker" data-title="vanJker" class="avatar" style="background: url(/images/loading.min.svg) no-repeat center;" onload="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}this.dataset.lazyloaded='';" onerror="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}"/>&nbsp;vanJker</a></span>&nbsp;<span class="post-publish" title='2024-03-30 12:17:31'>发布于 <time datetime="2024-03-30">2024-03-30</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/draft/" class="post-category" title="分类 - Draft"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Draft</a></span></div><div class="content"><p>This post is used to record the process of my English learning.</p></div><div class="post-footer">
<a href="/posts/english/">阅读全文</a><div class="post-tags"><i class="fa-solid fa-tags fa-fw me-1" aria-hidden="true"></i><a href='/tags/draft/' class="post-tag">Draft</a></div></div>
</article>
<article class="single summary" itemscope itemtype="http://schema.org/Article"><h2 class="single-title" itemprop="name headline"><span title="转载" class="icon-repost"><i class="fa-solid fa-share fa-fw" aria-hidden="true"></i></span><a href="/posts/oerv-pretask/">OERV 之 Pretask</a>
Expand All @@ -180,8 +179,7 @@
<a href="/posts/oerv-pretask/">阅读全文</a><div class="post-tags"><i class="fa-solid fa-tags fa-fw me-1" aria-hidden="true"></i><a href='/tags/risc-v/' class="post-tag">RISC-V</a><a href='/tags/openeuler/' class="post-tag">OpenEuler</a><a href='/tags/qemu/' class="post-tag">QEMU</a><a href='/tags/neofetch/' class="post-tag">Neofetch</a><a href='/tags/container/' class="post-tag">Container</a><a href='/tags/chroot/' class="post-tag">Chroot</a><a href='/tags/nspawn/' class="post-tag">Nspawn</a></div></div>
</article>
<article class="single summary" itemscope itemtype="http://schema.org/Article"><h2 class="single-title" itemprop="name headline"><span title="转载" class="icon-repost"><i class="fa-solid fa-share fa-fw" aria-hidden="true"></i></span><a href="/posts/deepin-kvm/">Deepin 20.9 KVM 安装和管理</a>
</h2><div class="post-meta"><span class="post-author"><span class="author"><i class="fa-solid fa-user-circle" aria-hidden="true"></i>
</span></span>&nbsp;<span class="post-publish" title='2024-03-28 12:21:48'>发布于 <time datetime="2024-03-28">2024-03-28</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/toolkit/" class="post-category" title="分类 - Toolkit"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Toolkit</a></span></div><div class="content"><p>本篇主要介绍在 deepin20.9 操作系统平台下,使用 KVM 虚拟化技术来创建和安装 Linux 发行版,并以创建安装 openEuler 22.03 LTS SP3 的 KVM 虚拟机作为示范,让学员领略 KVM 虚拟化技术的强大魅力。</p></div><div class="post-footer">
</h2><div class="post-meta"><span class="post-author"><a href="https://github.com/ccrysisa" title="作者"target="_blank" rel="external nofollow noopener noreferrer author" class="author"><img loading="lazy" src="https://avatars.githubusercontent.com/u/133117003?s=400&amp;v=4" alt="ccrysisa" data-title="ccrysisa" class="avatar" style="background: url(/images/loading.min.svg) no-repeat center;" onload="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}this.dataset.lazyloaded='';" onerror="this.title=this.dataset.title;for(const i of ['style', 'data-title','onerror','onload']){this.removeAttribute(i);}"/>&nbsp;ccrysisa</a></span>&nbsp;<span class="post-publish" title='2024-03-28 12:21:48'>发布于 <time datetime="2024-03-28">2024-03-28</time></span><span class="post-included-in">&nbsp;收录于 <a href="/categories/toolkit/" class="post-category" title="分类 - Toolkit"><i class="fa-regular fa-folder fa-fw" aria-hidden="true"></i> Toolkit</a></span></div><div class="content"><p>本篇主要介绍在 deepin20.9 操作系统平台下,使用 KVM 虚拟化技术来创建和安装 Linux 发行版,并以创建安装 openEuler 22.03 LTS SP3 的 KVM 虚拟机作为示范,让学员领略 KVM 虚拟化技术的强大魅力。</p></div><div class="post-footer">
<a href="/posts/deepin-kvm/">阅读全文</a><div class="post-tags"><i class="fa-solid fa-tags fa-fw me-1" aria-hidden="true"></i><a href='/tags/linux/' class="post-tag">Linux</a><a href='/tags/deepin/' class="post-tag">Deepin</a><a href='/tags/kvm/' class="post-tag">KVM</a><a href='/tags/qemu/' class="post-tag">QEMU</a><a href='/tags/openeuler/' class="post-tag">OpenEuler</a></div></div>
</article>
<article class="single summary" itemscope itemtype="http://schema.org/Article"><h2 class="single-title" itemprop="name headline"><span title="转载" class="icon-repost"><i class="fa-solid fa-share fa-fw" aria-hidden="true"></i></span><a href="/posts/c-preprocessor/">你所不知道的 C 语言: 前置处理器应用篇</a>
Expand Down
2 changes: 1 addition & 1 deletion docs/posts/deepin20.9/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -426,5 +426,5 @@ <h2 id="faq" class="heading-element">
<div class="noscript-warning">FixIt 主题在启用 JavaScript 的情况下效果最佳。</div>
</noscript>
</div><link rel="stylesheet" href="/lib/lightgallery/css/lightgallery-bundle.min.css"><link rel="preload" href="/lib/katex/katex.min.css" as="style" onload="this.removeAttribute('onload');this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/lib/katex/katex.min.css"></noscript><link rel="stylesheet" href="/lib/cookieconsent/cookieconsent.min.css"><script src="/lib/autocomplete/autocomplete.min.js" defer></script><script src="/lib/lightgallery/lightgallery.min.js" defer></script><script src="/lib/lightgallery/plugins/thumbnail/lg-thumbnail.min.js" defer></script><script src="/lib/lightgallery/plugins/zoom/lg-zoom.min.js" defer></script><script src="/lib/sharer/sharer.min.js" async defer></script><script src="/lib/katex/katex.min.js" defer></script><script src="/lib/katex/auto-render.min.js" defer></script><script src="/lib/katex/mhchem.min.js" defer></script><script src="/lib/cookieconsent/cookieconsent.min.js" defer></script><script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async defer></script><script src="/js/flyfish.js" defer></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","editLockTitle":"锁定可编辑代码块","editUnLockTitle":"解锁可编辑代码块","editable":true,"maxShownLines":10},"comment":{"enable":false},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验。"},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"enablePWA":true,"lightgallery":true,"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":true,"left":"\\begin{equation}","right":"\\end{equation}"},{"display":true,"left":"\\begin{equation*}","right":"\\end{equation*}"},{"display":true,"left":"\\begin{align}","right":"\\end{align}"},{"display":true,"left":"\\begin{align*}","right":"\\end{align*}"},{"display":true,"left":"\\begin{alignat}","right":"\\end{alignat}"},{"display":true,"left":"\\begin{alignat*}","right":"\\end{alignat*}"},{"display":true,"left":"\\begin{gather}","right":"\\end{gather}"},{"display":true,"left":"\\begin{CD}","right":"\\end{CD}"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50}};</script><script src="/js/theme.min.js" defer></script></body>
<noscript><link rel="stylesheet" href="/lib/katex/katex.min.css"></noscript><link rel="stylesheet" href="/lib/cookieconsent/cookieconsent.min.css"><script src="/lib/autocomplete/autocomplete.min.js" defer></script><script src="/lib/lightgallery/lightgallery.min.js" defer></script><script src="/lib/lightgallery/plugins/thumbnail/lg-thumbnail.min.js" defer></script><script src="/lib/lightgallery/plugins/zoom/lg-zoom.min.js" defer></script><script src="/lib/sharer/sharer.min.js" async defer></script><script src="/lib/katex/katex.min.js" defer></script><script src="/lib/katex/auto-render.min.js" defer></script><script src="/lib/katex/mhchem.min.js" defer></script><script src="/lib/cookieconsent/cookieconsent.min.js" defer></script><script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async defer></script><script src="/js/flyfish.js" defer></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","editLockTitle":"锁定可编辑代码块","editUnLockTitle":"解锁可编辑代码块","editable":true,"maxShownLines":10},"comment":{"enable":false},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验。"},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"data":{"id-1":{"title":"~/.vimrc"}},"enablePWA":true,"lightgallery":true,"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":true,"left":"\\begin{equation}","right":"\\end{equation}"},{"display":true,"left":"\\begin{equation*}","right":"\\end{equation*}"},{"display":true,"left":"\\begin{align}","right":"\\end{align}"},{"display":true,"left":"\\begin{align*}","right":"\\end{align*}"},{"display":true,"left":"\\begin{alignat}","right":"\\end{alignat}"},{"display":true,"left":"\\begin{alignat*}","right":"\\end{alignat*}"},{"display":true,"left":"\\begin{gather}","right":"\\end{gather}"},{"display":true,"left":"\\begin{CD}","right":"\\end{CD}"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50}};</script><script src="/js/theme.min.js" defer></script></body>
</html>
Loading

0 comments on commit 2fff689

Please sign in to comment.