std::optional 与 std::variant 对比 ​

面试考点 ​

optional 和 variant 都是 C++17 的值语义类型,面试官通过这道题考察你是否理解它们的本质区别:optional 表示"有或没有",variant 表示"是这个或那个"。两者的内存布局、使用场景和错误处理方式都不同。

核心概念 ​

std::optional<T> 表示一个可能不存在的 T 值,只有两种状态:有值或空。std::variant<T1, T2, ...> 表示一个值可以是多种类型中的某一种,始终持有一个值(除非进入 valueless_by_exception 状态)。

基本示例 ​

cpp
#include <iostream>
#include <optional>
#include <variant>
#include <string>
#include <vector>
#include <cmath>

// ============================
// 示例1:optional——可能没有值
// ============================

// 查找函数:可能找不到
std::optional<int> find_index(const std::vector<int>& vec, int target) {
    for (size_t i = 0; i < vec.size(); i++) {
        if (vec[i] == target) return static_cast<int>(i);
    }
    return std::nullopt;  // 没找到
}

void optional_demo() {
    std::vector<int> data = {10, 20, 30, 40};

    auto result = find_index(data, 30);
    if (result.has_value()) {
        std::cout << "找到,索引: " << *result << std::endl;
    }

    auto missing = find_index(data, 99);
    // value_or:没值时用默认值
    std::cout << "未找到,默认: " << missing.value_or(-1) << std::endl;
}

// ============================
// 示例2:variant——多种类型之一
// ============================

// JSON 值:可以是多种类型
using JsonValue = std::variant<
    std::nullptr_t,   // null
    bool,             // true/false
    int,              // 整数
    double,           // 浮点数
    std::string       // 字符串
>;

void print_json(const JsonValue& val) {
    std::visit([](const auto& v) {
        using T = std::decay_t<decltype(v)>;
        if constexpr (std::is_same_v<T, std::nullptr_t>) {
            std::cout << "null";
        } else if constexpr (std::is_same_v<T, bool>) {
            std::cout << (v ? "true" : "false");
        } else if constexpr (std::is_same_v<T, std::string>) {
            std::cout << "\"" << v << "\"";
        } else {
            std::cout << v;
        }
    }, val);
    std::cout << std::endl;
}

void variant_demo() {
    JsonValue v1 = 42;
    JsonValue v2 = "hello";
    JsonValue v3 = true;
    JsonValue v4 = nullptr;

    print_json(v1);  // 42
    print_json(v2);  // "hello"
    print_json(v3);  // true
    print_json(v4);  // null
}

// ============================
// 示例3:错误处理——optional vs variant
// ============================

// optional 方式:只知道成功或失败
std::optional<double> sqrt_opt(double x) {
    if (x < 0) return std::nullopt;
    return std::sqrt(x);
}

// variant 方式:可以携带错误信息
enum class MathError { NegativeInput, Overflow, DivideByZero };

std::variant<double, MathError> sqrt_var(double x) {
    if (x < 0) return MathError::NegativeInput;
    return std::sqrt(x);
}

void error_handling_demo() {
    // optional:只能知道失败了
    auto r1 = sqrt_opt(-1);
    if (!r1) std::cout << "optional: 计算失败" << std::endl;

    // variant:可以知道为什么失败
    auto r2 = sqrt_var(-1);
    if (std::holds_alternative<MathError>(r2)) {
        auto err = std::get<MathError>(r2);
        if (err == MathError::NegativeInput) {
            std::cout << "variant: 负数输入" << std::endl;
        }
    }
}

// ============================
// 示例4:组合使用
// ============================

// optional<variant>:可能没有值,有值时是多种类型之一
using MaybeJson = std::optional<JsonValue>;

MaybeJson parse_field(const std::string& field_name) {
    if (field_name == "name") return JsonValue{"Alice"};
    if (field_name == "age")  return JsonValue{30};
    if (field_name == "active") return JsonValue{true};
    return std::nullopt;  // 字段不存在
}

void combination_demo() {
    auto name = parse_field("name");
    auto unknown = parse_field("xxx");

    if (name) {
        std::cout << "name 存在: ";
        print_json(*name);
    }
    if (!unknown) {
        std::cout << "xxx 不存在" << std::endl;
    }
}

// ============================
// 示例5:内存布局对比
// ============================

void size_demo() {
    std::cout << "sizeof(optional<int>)    = " << sizeof(std::optional<int>) << std::endl;
    std::cout << "sizeof(optional<double>) = " << sizeof(std::optional<double>) << std::endl;

    std::cout << "sizeof(variant<int, double>)      = "
              << sizeof(std::variant<int, double>) << std::endl;
    std::cout << "sizeof(variant<int, double, string>) = "
              << sizeof(std::variant<int, double, std::string>) << std::endl;

    // optional<T>: sizeof(T) + bool + padding
    // variant<Ts...>: max(sizeof(Ts)...) + index + padding
}

// ============================
// 示例6:访问方式对比
// ============================

void access_demo() {
    // optional 的访问
    std::optional<int> opt = 42;
    int a = *opt;               // operator*(不检查)
    int b = opt.value();        // 有检查,空时抛 bad_optional_access
    int c = opt.value_or(0);    // 空时返回默认值

    // variant 的访问
    std::variant<int, std::string> var = 42;
    int d = std::get<int>(var);         // 按类型获取,类型错误时抛异常
    int e = std::get<0>(var);           // 按索引获取
    int* f = std::get_if<int>(&var);    // 不抛异常,返回指针
    // std::visit 是最推荐的访问方式

    std::cout << a << " " << b << " " << c << " "
              << d << " " << e << " " << *f << std::endl;
}

int main() {
    std::cout << "=== optional ===" << std::endl;
    optional_demo();

    std::cout << "\n=== variant ===" << std::endl;
    variant_demo();

    std::cout << "\n=== 错误处理 ===" << std::endl;
    error_handling_demo();

    std::cout << "\n=== 组合使用 ===" << std::endl;
    combination_demo();

    std::cout << "\n=== 内存大小 ===" << std::endl;
    size_demo();

    std::cout << "\n=== 访问方式 ===" << std::endl;
    access_demo();

    return 0;
}

optional vs variant 对比 ​

特性std::optional<T>std::variant<T1, T2, ...>
语义有值或没有值是类型 A 或类型 B 或...
状态数2(有/无)N(N 种类型)
空状态nullopt(正常状态)valueless_by_exception(异常状态)
内存布局T + boolmax(T1, T2, ...) + index
访问方式*, value(), value_or()get, get_if, visit
适用场景可选参数、可能失败的查找多态值、类型安全联合
错误信息只知道失败可以携带错误类型和信息

常见问题 ​

什么时候用 optional,什么时候用 variant?

如果只需要表示"有或没有",用 optional。如果需要表示"成功值或错误信息",用 variant<Result, Error>(或 C++23 的 std::expected)。如果需要存储多种不同类型的值,用 variant。

optional 和 variant 能嵌套吗?

可以。optional<variant<...>> 表示"可能没有值,有值时是多种类型之一"。variant<optional<T>, ...> 也合法但通常不推荐,会增加理解难度。

C++23 的 std::expected 和它们是什么关系?

std::expected<T, E> 专门用于错误处理,语义是"要么是成功值 T,要么是错误值 E"。它比 variant<T, Error> 更语义化,比 optional<T> 能携带更多错误信息。

适用场景 ​

场景推荐类型
函数可能没有返回值optional
配置项可能缺失optional
JSON/XML 值(多种类型)variant
状态机(多种状态)variant
成功值或错误码variant 或 expected(C++23)
可选参数带默认值optional + value_or

注意事项 ​

  • optional 的 operator* 不检查是否有值
  • variant 的 get 类型不匹配时抛 bad_variant_access
  • variant 要求第一个类型可默认构造(否则用 monostate)
  • optional 不支持引用类型
  • 两者都不做堆分配,都是值语义

总结 ​

optional 表示"有或没有",variant 表示"是 A 还是 B"。optional 适合可选值和简单的失败表示,variant 适合多态值和携带错误信息的结果。两者都是值语义、不做堆分配。面试中要能说出它们的语义区别、内存布局差异、适用场景,以及 C++23 的 std::expected 作为错误处理的更佳选择。