第 16 课2026.09.21
把已有字符串资源转交给另一个已存在变量。
第 16 课:移动赋值复用字符串
- 日期:2026-09-21
- 课程序号:第 16 课
- 知识点:移动赋值复用字符串
用途或适用场景
把已有字符串资源转交给另一个已存在变量。
核心概念
上一课使用移动构造;本课把 std::move 的结果赋给已存在的目标字符串。
最小代码或操作示例
text
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string title = "C++";
std::string destination = "旧标题";
destination = std::move(title);
std::cout << destination << "\n";
}3~5 分钟练习
把 destination 初值改为“草稿”。
参考答案
移动后仍输出 C++;不依赖 title 移动后的具体内容。
与上一课的联系
沿用第 15 课的 title 字符串与 std::move;本课只新增向已存在的 destination 执行移动赋值;完成练习后下一课可只移动 Lesson 的一个字符串成员。
时效校验
时效校验:2026-09-24(ISO C++ FAQ 当前版;std::move 与移动赋值需 C++11+;已用 Apple Clang 21.0.0 按 C++11 编译运行,未见本课方案的废弃说明)。