Skip to content

docs(cpp): 补全引用基础练习答案 - #211

Merged
Charliechen114514 merged 1 commit into
Awesome-Embedded-Learning-Studio:mainfrom
xiaoshuaijie:ch04-3
Sep 5, 2026
Merged

docs(cpp): 补全引用基础练习答案#211
Charliechen114514 merged 1 commit into
Awesome-Embedded-Learning-Studio:mainfrom
xiaoshuaijie:ch04-3

Conversation

@xiaoshuaijie

Copy link
Copy Markdown
Collaborator

概述

本 PR 为第一卷第 4 章《03-references:引用》的三道练习题补全参考答案,是练习答案补全系列(##201、##203、##206、##207)的延续。答案统一放在 VitePress ::: details 折叠块内,默认收起,不干扰正文阅读;读者做完题后可展开对照。

主要变更

✅ 完成内容

  • 练习一:用引用修改数组

    • 按题目提示采用 std::array<int, 5>& 传参,替代无法保留长度信息的 C 风格数组
    • 答案内含完整可编译程序、编译命令(g++ -std=c++17 -Wall -Wextra)与实测运行结果
  • 练习二:找错(悬空引用辨析)

    • 用表格逐行给出"编译错误 vs 运行时未定义行为"的结论与原因
    • 重点澄清了本题最易混淆的点:制造悬空引用(行 A int& r = get_value();)本身可以编译,通过它读写才是 UB——与题目"二分法"表述的差异单独用一段说明
    • 给出三种错误的修正方向:按值返回 get_value、声明时必须初始化引用、传入具名左值代替字面量
    • 附完整修正版代码
  • 练习三:链式配置器

    • Config 类两个 setter 均返回 Config&,成员用 int width_{} / int height_{} 就地初始化
    • 演示 c.set_width(800).set_height(600); 链式调用

📝 技术亮点

  • 练习二没有停留在"哪个行报错",而是区分了 错误状态(悬空引用,可编译)与 触发 UB 的动作(访问悬空引用)两个阶段,并给出最小复现代码片段(std::cout << r;)
  • 所有断言均经本地编译实测(GCC 诊断与文中结论逐字吻合),修正版以 -Wall -Wextra 零警告通过

📄 变更文件

测试

本机环境:Windows 10 x64 + MinGW-w64 GCC 8.1.0

  • 练习一答案通过 g++ -std=c++17 -Wall -Wextra ex1.cpp -o ex1 && ./ex1 编译运行,输出与文中一致(零警告)
  • 练习二原错误代码逐行验证:行 B/C/D 均产生编译错误(错误信息见上),行 A 仅触发 [-Wreturn-local-addr] / [-Wunused-variable] 警告,与解析结论一致
  • 练习二修正版通过同一命令编译运行,-Wall -Wextra 零警告
  • 练习三答案编译运行通过,链式调用正常
  • markdownlint documents/vol1-fundamentals/ch04/03-references.md 通过
  • .venv Python 运行 scripts/validate_frontmatter.py:991 个文件全部通过,0 错误
  • 3 对 ::: details ... ::: 折叠块配对正确,VitePress 渲染无异常

后续计划

ch04 尚有两篇文章的练习未补答案,计划后续 PR 继续:

  • 02-pointer-arithmetic.md(3 道练习)
  • 04-smart-ptr-preview.md(2 道练习)

相关 Issue

无(练习答案补全系列任务)

@Charliechen114514 Charliechen114514 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

嗯嗯,这个我确认了一下,也是没问题的

int height_{};

public:
Config& set_width(int width)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

嗯嗯,写的很好,这个后面bro学习设计模式的时候,Builder模式的链条形式就是这样的,到时候我的ZerOS——一个玩具的C++23的RTOS的TCB控制块构建就是这样处理的

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好的好的

@Charliechen114514
Charliechen114514 merged commit 903bdc1 into Awesome-Embedded-Learning-Studio:main Sep 5, 2026
5 checks passed
@xiaoshuaijie
xiaoshuaijie deleted the ch04-3 branch September 5, 2026 12:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants