【四周连更】RAII 与左右值:从「代码负债」到「内存优雅」

我说gemini是最有活人味的llm有懂的吗。
基于我blog的一些整理以及和他的chat,在我的指导下写成

原文在我blog上,但是内容比较冗长像列提纲,需要大修 :enraged_face:

(因为还在建设就先没放地址了)

给gemini的部分prompt

然后结构大概是:
认识值类型和引用类型(例子,常用的数组引用防止退化)

构造class的方式,以及initializer_list(小心贪婪匹配,但是其他情况下还是很好用的,在return时,或者复合构造时(vector里面装vector之类的))

右值,将亡值。你知道这个将要消亡。
右值相关的标准库,make_move_iterator等……

在自定义的class内,当一个值知道自己要消亡时,我们可以怎么做(移动构造)
附录,标准库中的约束,复制构造被delete的unique_ptr

精确地控制:move和forward

auto的推导(占位,推导类型,泛型(func(auto xxx)))

concept,更泛用的类型,callback,ismoveable……

关于this指针,func const &&到底是什么,以及deducing this的用法(CRTP,lambda,以及替代写这几个函数)

类型体操,更现代的cast,替代typedef的using,dectval,去掉cv限定的……

扩展:结构化绑定和包装类型tuple,optional.expected,variant,any(

0. 引言:Agent 时代,为什么还要懂 C++ 的类型与内存?

现在 AI Agent 写代码确实快,需求给得清楚时,业务功能蹭蹭往外蹦。但用久了你大概也会发现一个现象:代码是负债,功能才是财富。

有些 Agent 在需求还模糊、边界还没抠明白的时候,特别喜欢「过度发挥」:该复用的没复用、悄悄重复造轮子,或者堆出一堆绕了好几层的抽象,表面上跑通了,实际上改一行就牵一发而动全身,维护成本全算在开发者头上。

而 C++ 最迷人的地方就在这里:它对内存的控制、零开销抽象(不用的特性不付代价,手写代码能做到的抽象也不额外加运行时开销),以及那套极其完备的类型系统,简直像一件精密又可爱的机械工艺品!:sparkles:

有时候你不需要跟 Agent 掰扯半天自然语言,只要你能精确地表达你到底需要一个什么样的类型、谁拥有这块资源、这个值什么时候死,很多「代码负债」从源头就被挡住了。

今天这整篇,我们就顺着 RAII → 左右值与移动 → 类型推导与约束 → Deducing This → 类型体操与工具库 这条主线,把这些机制拆开、揉碎,多上几个能直接上手的例子。学吧!:flexed_biceps:

1. 认识值类型与引用类型:别让你的信息悄悄溜走

在 C++ 里,理解内存和所有权的第一步,是分清值类型和引用类型。值类型像是把东西装进自己的小盒子,拿走就拿走了;引用类型更像是给某块已经存在的内存贴上一张便利贴,顺着便利贴就能摸回去。

1.1 变式一:普通值传递 vs 引用传递

C++

#include <iostream>
#include <string>

void take_by_value(std::string s) {
    s += " [inside value]"; // 改的是拷贝出来的副本
}

void take_by_lref(std::string& s) {
    s += " [inside lref]";  // 直接改调用者手里的那份
}

void inspect_const_ref(const std::string& s) {
    // 既能接左值,也能接右值(临时对象),还不允许乱改
    std::cout << "len = " << s.size() << ", content = " << s << "\n";
}

int main() {
    std::string msg = "Hello";
    take_by_value(msg);
    std::cout << msg << "\n"; // 依然是 Hello

    take_by_lref(msg);
    std::cout << msg << "\n"; // 变成 Hello [inside lref]

    inspect_const_ref(msg);
    inspect_const_ref(std::string("Temp") + "!"); // 临时右值也能稳稳接住
}

1.2 变式二:最常用的数组引用——防止数组退化(decay)

写 C++ 很常见的一个「小失忆」是:数组传给函数时,会退化(decay)成指向首元素的指针。一旦退化,长度信息就丢了,sizeof(arr) 算出来的只是指针大小(比如 64 位下通常是 8 字节),而不是整个数组占多大。

用数组引用可以把长度 N 死死焊在类型里:

C++

#include <array>
#include <cstddef>
#include <iostream>

// 1. 退化版本:传进来的是 int*,N 丢了
void bad_decay(int* arr, std::size_t n) {
    for (std::size_t i = 0; i < n; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";
}

// 2. 数组引用版本:只接受「恰好 N 个 int 的数组」
template <std::size_t N>
void lock_array(int (&arr)[N]) {
    std::cout << "Locked array of size " << N << ": ";
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << "\n";
}

// 3. 现代 C++ 很多时候直接用 std::array<T, N> 更省心
void use_std_array(const std::array<int, 4>& arr) {
    std::cout << "std::array size = " << arr.size() << "\n";
}

int main() {
    int raw[4] = {10, 20, 30, 40};
    bad_decay(raw, 4);
    lock_array(raw); // N 自动推导为 4!如果传 int[3] 会直接编译报错

    std::array<int, 4> safe_arr{10, 20, 30, 40};
    use_std_array(safe_arr);
}

小贴士:注意 int (&arr)[N] 的括号不能省!如果写成 int &arr[N],意思是「由 N 个 int& 组成的数组」,而 C++ 里不存在引用的数组,直接编译不过。

2. 构造 class 的方式与 std::initializer_list:又香又得防着点

构造一个类有很多姿势:直接初始化、拷贝初始化、列表初始化(花括号 {}),还有委托构造、继承构造等等。其中 std::initializer_list 特别有意思——它像个甜心小恶魔,用对了超级顺手,用错了也会搞出惊喜。

2.1 变式一:日常构造与 return 时的花括号复合构造

在 return 或嵌套构造容器时,花括号列表能让代码干净很多:

C++

#include <vector>

struct Point2D {
    int x{};
    int y{};
};

struct MatrixRow {
    std::vector<int> values;
};

Point2D make_origin() {
    return {0, 0};
}

std::vector<std::vector<int>> make_grid() {
    return {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
}

std::vector<MatrixRow> make_rows() {
    return {
        MatrixRow{{10, 20}},
        MatrixRow{{30, 40, 50}}
    };
}

2.2 变式二:小心 std::initializer_list 的「贪婪匹配」

当类里同时有「普通构造函数」和「接受 std::initializer_list<T> 的构造函数」时,只要用 {} 初始化且类型能转过去,std::initializer_list 往往会抢先截胡(贪婪匹配)。

C++

#include <initializer_list>
#include <iostream>
#include <vector>

struct Box {
    std::vector<int> items;

    Box(int count, int val) : items(count, val) {
        std::cout << "Box(int, int) -> size=" << items.size() << "\n";
    }

    Box(std::initializer_list<int> init) : items(init) {
        std::cout << "Box(initializer_list<int>) -> size=" << items.size() << "\n";
    }
};

int main() {
    Box b1(3, 7);   // 圆括号:走 Box(int, int),3 个 7
    Box b2{3, 7};   // 花括号:贪婪匹配!走 initializer_list,只有 2 个元素 [3, 7]

    std::vector<int> v_count(4, 9); // 4 个 9
    std::vector<int> v_list{4, 9};  // 两个元素:4 和 9
    std::cout << "v_count.size()=" << v_count.size()
              << ", v_list.size()=" << v_list.size() << "\n";
}

3. 右值、将亡值与移动语义:当一个对象知道自己要消亡

在 C++ 里,表达式不只是「左值(lvalue)」和「纯右值(prvalue)」。还有一个特别关键的概念叫将亡值(xvalue,eXpiring value)——它还是一个有身份的对象,但它的生命周期马上就要结束了,资源随时可以被拿走。

3.1 标准库里和右值/移动相关的好帮手

  • std::move:把左值转成右值引用(xvalue),表达「允许按移动语义对待它」。本身不搬运数据。

  • std::forward:在模板转发引用(T&&)中,保留参数原本的左值/右值属性往下传。

  • std::make_move_iterator:把普通迭代器包成移动迭代器,解引用得到 T&&,把批量拷贝变成批量移动。

  • std::exchange:替换旧值并返回旧值,写移动构造和移动赋值时极其顺手。

C++

#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<std::string> src = {
        "very_long_string_alpha_001",
        "very_long_string_beta_002",
        "very_long_string_gamma_003"
    };
    std::vector<std::string> dst;
    dst.reserve(src.size());

    dst.insert(
        dst.end(),
        std::make_move_iterator(src.begin()),
        std::make_move_iterator(src.end())
    );

    std::cout << "dst[0] = " << dst[0] << "\n";
    std::cout << "src[0] size after move = " << src[0].size() << "\n";
}

3.2 自定义 class:当一个值知道自己要消亡时,我们怎么做?

移动构造函数接管资源并把源对象置为安全可析构状态,且强烈建议加上 noexcept(否则如 std::vector 扩容时为了维持强异常安全保证,可能放弃移动而退回拷贝)。

C++

#include <cstddef>
#include <cstring>
#include <iostream>
#include <utility>
#include <vector>

class Buffer {
public:
    explicit Buffer(std::size_t n)
        : size_(n), data_(n ? new char[n] : nullptr) {
        if (data_) {
            std::memset(data_, 'A', size_);
        }
    }

    ~Buffer() {
        delete[] data_;
    }

    Buffer(const Buffer& other)
        : size_(other.size_), data_(other.size_ ? new char[other.size_] : nullptr) {
        if (data_ && other.data_) {
            std::memcpy(data_, other.data_, size_);
        }
    }

    Buffer& operator=(const Buffer& other) {
        if (this == &other) return *this;
        char* fresh = other.size_ ? new char[other.size_] : nullptr;
        if (fresh && other.data_) {
            std::memcpy(fresh, other.data_, other.size_);
        }
        delete[] data_;
        data_ = fresh;
        size_ = other.size_;
        return *this;
    }

    Buffer(Buffer&& other) noexcept
        : size_(std::exchange(other.size_, 0)),
          data_(std::exchange(other.data_, nullptr)) {}

    Buffer& operator=(Buffer&& other) noexcept {
        if (this == &other) return *this;
        delete[] data_;
        size_ = std::exchange(other.size_, 0);
        data_ = std::exchange(other.data_, nullptr);
        return *this;
    }

    std::size_t size() const noexcept { return size_; }

private:
    std::size_t size_{0};
    char* data_{nullptr};
};

int main() {
    std::vector<Buffer> pool;
    pool.reserve(1);
    pool.emplace_back(1024);
    pool.push_back(Buffer(2048));
    std::cout << "pool size = " << pool.size() << "\n";
}

3.3 附录:标准库中的约束与 std::unique_ptr 为什么 = delete 拷贝构造?

std::unique_ptr 表示独占所有权。如果允许拷贝,两份指针都会试图在析构时释放同一块资源,导致双重释放(UB)。因此它把拷贝构造和拷贝赋值标为 = delete,迫使所有权转移必须通过 std::move 显式发生。

C++

#include <iostream>
#include <memory>
#include <utility>

struct Worker {
    int id;
    explicit Worker(int i) : id(i) {}
    ~Worker() { std::cout << "Worker " << id << " destroyed\n"; }
};

int main() {
    auto p1 = std::make_unique<Worker>(7);
    // auto p2 = p1; // 编译错误:拷贝构造已删除
    auto p2 = std::move(p1);
    if (!p1) {
        std::cout << "Ownership moved to p2\n";
    }
}

3.4 精确控制:std::move 与 std::forward

C++

#include <iostream>
#include <string>
#include <utility>

void sink(std::string& s) { std::cout << "lvalue: " << s << "\n"; }
void sink(std::string&& s) { std::cout << "rvalue: " << s << "\n"; }

template <typename T>
void relay(T&& arg) {
    sink(std::forward<T>(arg));
}

int main() {
    std::string name = "Alice";
    relay(name);               // 转发为 lvalue
    relay(std::string("Bob")); // 转发为 rvalue
    relay(std::move(name));    // 转发为 rvalue
}

4. auto 推导、auto func() -> 与 concept

auto 不仅能做变量和泛型参数占位符,还能配合尾置返回类型(trailing return type)写成 auto func(...) -> RetType 这种形式。

4.1 auto 占位、泛型参数与尾置返回类型 auto func() ->

尾置返回类型在两种情况下特别好用:

  1. 返回类型依赖函数参数(比如用 decltype(...) 写表达式时,参数名在 -> 之后已经可见了);

  2. 返回类型本身很绕(比如函数指针、数组引用、嵌套模板),把函数头放前面、返回类型放 -> 后面,视线会顺很多。

C++

#include <iostream>
#include <string>
#include <utility>
#include <vector>

// 1. 返回类型依赖参数表达式
template <typename A, typename B>
auto add_and_pick(A&& a, B&& b) -> decltype(std::forward<A>(a) + std::forward<B>(b)) {
    return std::forward<A>(a) + std::forward<B>(b);
}

// 2. 尾置返回类型:返回一个「指向 3 个 int 数组的引用」
auto get_row_ref(int (&grid)[2][3], int row) -> int (&)[3] {
    return grid[row];
}

// 3. 泛型参数 func(auto x)
void print_item(const auto& x) {
    std::cout << x << "\n";
}

int main() {
    std::cout << add_and_pick(3, 4.5) << "\n";

    int g[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int (&r1)[3] = get_row_ref(g, 1);
    r1[0] = 99;
    std::cout << "g[1][0] = " << g[1][0] << "\n";

    print_item(std::string("auto + trailing return is clean"));
}

4.2 concept:更泛用的约束(movable、可调用/回调、requires 表达式)

C++

#include <concepts>
#include <iostream>
#include <string>
#include <utility>

template <typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};

template <std::movable T>
void accept_movable(T&& val) {
    T local = std::move(val);
    std::cout << "Moved: " << local << "\n";
}

template <typename Callback>
concept IntCallback = std::invocable<Callback, int>;

void run_steps(int n, IntCallback auto cb) {
    for (int i = 1; i <= n; ++i) cb(i);
}

int main() {
    std::string s = "hello";
    accept_movable(std::move(s));
    run_steps(2, [](int k) { std::cout << "step " << k << "\n"; });
}

5. 关于 this 指针、func const && 与 Deducing This

5.1 func const && 到底是什么?

成员函数末尾写 const &&,表示该成员函数只能由一个 const 右值 调用。通常用于「只读临时对象/右值」的特定消费或观察逻辑,避免普通左值误入。

C++

#include <iostream>
#include <string>

struct Token {
    std::string value;

    std::string inspect_const_rvalue() const && {
        return "[const&&] " + value;
    }
};

int main() {
    const Token t{"secret"};
    // 显式转为 const Token&& 后调用
    std::cout << static_cast<const Token&&>(t).inspect_const_rvalue() << "\n";
}

5.2 Deducing This(C++23):替代多份重载、简化 CRTP、递归 Lambda

通过在形参列表首个位置写 this auto&& self(或 this const auto& self),编译器直接把对象本身和值类别推导成显式参数 self。

C++

#include <iostream>
#include <string>
#include <utility>

struct Boxed {
    std::string payload = "init";

    // 一份函数适配多种 cv 与引用场景
    decltype(auto) access(this auto&& self) {
        return std::forward<decltype(self)>(self).payload;
    }
};

// 简化 CRTP:基类直接通过 this self 调用派生类接口
struct Named {
    void print_name(this const auto& self) {
        std::cout << "Name: " << self.name() << "\n";
    }
};

struct User : Named {
    const char* name() const { return "gopher_cpp"; }
};

int main() {
    Boxed b;
    b.access() = "modified";
    std::cout << b.access() << "\n";

    User u;
    u.print_name();

    // 递归 lambda
    auto fib = [](this const auto& self, int n) -> int {
        if (n <= 1) return n;
        return self(n - 1) + self(n - 2);
    };
    std::cout << "fib(7) = " << fib(7) << "\n";
}

6. 类型体操:现代 cast、离谱类型与 using、decltype / decltype(auto)

6.1 为什么 using 比老式语法救命?看看那些「离谱类型」

C++ 的声明语法有个经典「螺旋法则」:修饰符顺着名字往外绕,遇到括号就拐弯。一旦出现指向函数的指针、指向数组的指针,或者数组里存着函数指针,裸写声明简直像在看摩斯密码!

用 using 把中间层拆成小积木,立刻清爽很多:

C++

#include <iostream>

int add_two(int a, int b) { return a + b; }
int mul_two(int a, int b) { return a * b; }

// 1. 指向函数的指针:接受 (int, int) 返回 int 的函数指针
using BinOpPtr = int (*)(int, int);

// 2. 指向数组的指针:指向「长度为 3 的 int 数组」的指针
using Arr3Ptr = int (*)[3];

// 3. 存着函数指针的数组:长度为 2 的数组,每个元素都是 BinOpPtr
using OpTable = BinOpPtr[2];

// 对比一下:如果不写 using,数组里存函数指针裸写长这样:
// int (*raw_table[2])(int, int) = { add_two, mul_two };

// 甚至还能写「返回函数指针的函数」
using MakeOpFn = BinOpPtr (*)(bool);

BinOpPtr choose_op(bool pick_mul) {
    return pick_mul ? &mul_two : &add_two;
}

int main() {
    // 离谱 1:函数指针
    BinOpPtr fn = &add_two;
    std::cout << "fn(2, 3) = " << fn(2, 3) << "\n";

    // 离谱 2:指向数组的指针
    int arr3[3] = {10, 20, 30};
    Arr3Ptr p_arr = &arr3;
    std::cout << "(*p_arr)[1] = " << (*p_arr)[1] << "\n";

    // 离谱 3:数组存着函数指针
    OpTable table = { &add_two, &mul_two };
    std::cout << "table[0](4, 5) = " << table[0](4, 5) << "\n";
    std::cout << "table[1](4, 5) = " << table[1](4, 5) << "\n";

    // 离谱 4:指向「返回函数指针的函数」的指针
    MakeOpFn maker = &choose_op;
    std::cout << "maker(true)(3, 4) = " << maker(true)(3, 4) << "\n";
}

6.2 现代 cast、decltype、decltype(auto) 与「很骚的」decltype(expr) var = xxx

  • 现代 cast:用 static_cast、const_cast、reinterpret_cast、dynamic_cast 替代 C 风格 (T)x,意图更明确。

  • decltype(auto):既想让编译器自动推导类型,又想保留 decltype 对表达式值类别的精确规则(比如返回引用时把引用也保住,而不是像普通 auto 那样剥掉引用按值返回)。

  • 一个很骚的用法:decltype(expr) var = xxx; 有时候你手头已经有了一个现成表达式 expr(比如某个字段访问 obj.field、某个计算表达式 a + b、或者某个回调调用结果),你想新建一个变量 var,直接复用 expr 推导出来的那个精确类型,顺便给它赋一个初始值 xxx——这就叫 decltype(expr) var = xxx;! 注意哦:expr 和 xxx 可以是两回事!decltype(expr) 决定 var 的类型,xxx 负责初始化 var(当然 xxx 必须能初始化那个推导出来的类型)。

C++

#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

struct Record {
    int id{0};
    std::string tag{"default"};
};

// decltype(auto) 保留引用性:返回元素引用,调用者可以直接改容器里的元素
decltype(auto) pick_at(std::vector<int>& v, std::size_t idx) {
    return v[idx]; // v[idx] 是 int&,decltype(auto) 推导为 int&
}

int main() {
    std::vector<int> nums{10, 20, 30};
    pick_at(nums, 1) = 200; // 直接改到了 nums[1]
    std::cout << "nums[1] = " << nums[1] << "\n";

    // 「很骚的」用法:decltype(expr) var = xxx;
    Record rec{42, "alpha"};

    // 拿 rec.id 的类型(int)做变量类型,但初值给的是 999
    decltype(rec.id) backup_id = 999;

    // 拿 rec.tag 的类型(std::string)做变量类型,但初值拼了一个新字符串
    decltype(rec.tag) next_tag = std::string("beta_") + "v2";

    // 小心括号!rec.id 是 int,(rec.id) 是左值表达式,decltype((rec.id)) 是 int&
    // 如果用 decltype((rec.id)) 绑定引用,改 ref_id 就会改 rec.id
    decltype((rec.id)) ref_id = rec.id;
    ref_id = 100;

    std::cout << "rec.id=" << rec.id
              << ", backup_id=" << backup_id
              << ", next_tag=" << next_tag << "\n";
}

6.3 std::declval 与去掉 CV 限定(std::remove_cv_t / std::remove_cvref_t)

C++

#include <string>
#include <type_traits>
#include <utility>

struct OnlyArgCtor {
    OnlyArgCtor() = delete;
    explicit OnlyArgCtor(int) {}
    double score() const { return 9.5; }
};

int main() {
    // 无需构造 OnlyArgCtor,直接探测 score() 的返回类型
    using ScoreRet = decltype(std::declval<const OnlyArgCtor&>().score());
    static_assert(std::is_same_v<ScoreRet, double>);

    // 去掉 cv 限定与引用
    using Raw = std::remove_cvref_t<const volatile std::string&>;
    static_assert(std::is_same_v<Raw, std::string>);
}

7. 扩展工具库:结构化绑定、包装类型与调用/地址护栏

7.1 结构化绑定与 std::tuple

C++

#include <iostream>
#include <string>
#include <tuple>
#include <utility>

int main() {
    std::pair<int, std::string> p{1, "ok"};
    auto [code, msg] = p;
    std::cout << code << ": " << msg << "\n";

    std::tuple<int, int, const char*> box{3, 4, "px"};
    auto& [w, h, unit] = box;
    w *= 2;
    std::cout << w << "x" << h << unit << "\n";
}

7.2 包装类型:std::optional、std::expected、std::variant、std::any

C++

#include <any>
#include <expected>
#include <iostream>
#include <optional>
#include <string>
#include <variant>

template <typename... Ts>
struct Visitor : Ts... {
    using Ts::operator()...;
};

std::expected<int, std::string> divide_positive(int a, int b) {
    if (b == 0) return std::unexpected("division by zero");
    return a / b;
}

int main() {
    std::optional<int> opt;
    std::cout << opt.value_or(-1) << "\n";

    if (auto r = divide_positive(10, 2)) {
        std::cout << "10 / 2 = " << *r << "\n";
    }

    std::variant<int, std::string> v = 123;
    std::visit(Visitor{
        [](int x) { std::cout << "int -> " << x << "\n"; },
        [](const std::string& s) { std::cout << "str -> " << s << "\n"; }
    }, v);

    std::any a = std::string("wrapped");
    if (auto* sp = std::any_cast<std::string>(&a)) {
        std::cout << "any string: " << *sp << "\n";
    }
}

7.3 解决灵活调用与取址陷阱:std::ref、std::invoke、std::addressof

C++

#include <functional>
#include <iostream>
#include <memory>
#include <utility>

struct EvilAddr {
    int x = 1;
    int operator&() const { return 404; } // 重载取址运算符捣乱
};

struct Runner {
    int base = 10;
    int add(int delta) const { return base + delta; }
};

template <typename F, typename... Args>
decltype(auto) invoke_fwd(F&& f, Args&&... args) {
    return std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
}

int main() {
    int count = 0;
    auto bump = [](int& n) { n += 5; };
    invoke_fwd(bump, std::ref(count));
    std::cout << "count = " << count << "\n";

    Runner r{20};
    std::cout << "invoke member fn = " << invoke_fwd(&Runner::add, r, 5) << "\n";
    std::cout << "invoke member obj = " << invoke_fwd(&Runner::base, r) << "\n";

    EvilAddr evil;
    std::cout << "&evil = " << (&evil) << "\n";
    std::cout << "std::addressof(evil) = " << std::addressof(evil) << "\n";
}

结语

代码是负债,功能才是财富。在 Agent 越来越能干的今天,真正能把代码稳稳托住的,往往是我们对生命周期、所有权和类型的清晰表达。希望这篇完整草稿对你的发帖和抽奖好运都有帮助!