Menu
CoddyTech

仅可移动的所有权

Coddy 面向 Swift 开发者的 C++ 课程的第 41 课,共 48 课。

Swift 中的 String 和 Array 等值在赋值时会被复制,并通过写时复制机制降低复制开销,因此源值仍可使用。标记为 ~Copyable 的类型只能移动:赋值会消耗源值,编译器会拒绝之后对它的任何使用。C++ 要求使用 std::move 这样的右值上下文。它是一种允许移动操作的强制转换,本身并不执行移动,而且不会阻止之后继续使用源值。C++ 的 unique_ptr 只能移动。移动会转移所有权,并使源值变为空;其他被移出的对象不一定具有指定的值。

Swift

struct Token: ~Copyable {
    let name: String
}

func demo() {
    var a = "oak"
    let b = a
    a += "!"
    print(a, b)
    let t = Token(name: "pine")
    let u = t
    print(u.name)
}
demo()

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
auto a=std::make_unique<std::string>("oak");auto b=std::move(a);std::cout<<std::boolalpha<<static_cast<bool>(a)<<" "<<*b<<"\n";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示概念,不应假定源代码和目标代码的输出相同。

challenge icon

挑战

简单

输入:整数。Box 通过 unique_ptr 拥有一个整数。移动 Box 会转移所有权;has_value 返回它是否拥有一个值,get 返回所拥有的值,如果为空则返回零。驱动程序先进行移动构造,然后进行移动赋值;移动后的对象必须为空。复制操作已删除。

可编辑模块:Box.cpp、Box.hpp。每种必需类型都有自己的命名头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在指定情况下独立检查公共 API 的行为。在 API 内返回值,而不是打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。

亲手试试

#include <type_traits>
#include "Box.hpp"
#include <iostream>
int main(){ static_assert(!std::is_copy_constructible<Box>::value,"This owning type must not be copyable");
{Box a(17);Box b(std::move(a));if(a.has_value()||!b.has_value()||b.get()!=17)return 21;Box c(2);c=std::move(b);if(b.has_value()||c.get()!=17)return 22;c=std::move(c);if(!c.has_value()||c.get()!=17)return 23;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;Box a(n);Box b(std::move(a));Box c(0);c=std::move(b);std::cout<<std::boolalpha<<a.has_value()<<" "<<b.has_value()<<" "<<c.get()<<"\n";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Swift 开发者的 C++中的所有课

自己练习: C++ 在线编译器