第 17 课2026.09.22
课程对象需要保留自己的时长,只接收另一对象的标题时,避免误移动整个对象。
第 17 课:只移动 Lesson 的标题成员
- 日期:2026-09-22
- 课程序号:第 17 课
- 知识点:对结构体的单个成员执行移动赋值
用途或适用场景
课程对象需要保留自己的时长,只接收另一对象的标题时,避免误移动整个对象。
核心概念
std::move(source.title) 只把标题作为移动赋值来源;destination.minutes 不会因此改变。不要依赖移动后 source.title 的具体内容。
最小代码或操作示例
cpp
#include <iostream>
#include <string>
#include <utility>
struct Lesson { std::string title; int minutes; };
int main() {
Lesson source{"C++", 5};
Lesson destination{"草稿", 1};
destination.title = std::move(source.title);
std::cout << destination.title << " " << destination.minutes << '\n'; // C++ 1
}3~5 分钟练习
把 destination.minutes 改为 3,再移动标题并确认输出。
参考答案
把目标对象初始化为 Lesson destination{"草稿", 3};,输出 C++ 3;本课没有移动时长成员。
与上一课的联系
沿用第 16 课对已有字符串执行移动赋值的方式,并复用前面学过的 Lesson 结构体;本课只把目标改成 destination.title;下一课可对比移动整个 Lesson 时目标时长是否也变化。
时效校验
时效校验:2026-09-24(已打开 Standard C++ 的 C++11 移动语义及默认移动操作说明;本课使用 C++11 起支持的 std::move,未见废弃标记)。