Every advantage has a cost.优势的另一面,就是代价。
This compares Safe Rust with modern C++ using practices such as RAII, rather than comparing an idealized Rust with the worst possible C++.这里比较 Safe Rust 与采用 RAII 等实践的现代 C++,而不是用理想化的 Rust 对比最糟糕的 C++。
Rust
Accept constraints up front for clearer safety boundaries用前期约束,换更清晰的安全边界
C++
Extend existing systems with an established ecosystem and control用成熟生态与控制力,延续系统资产
Claims about convenience or maintenance costs are engineering judgments based on mechanisms, not statistical conclusions that apply to every team.“更省事”“维护代价”等属于基于机制的工程判断,不是所有团队都适用的统计结论。
Eight dimensions, without invented scores.八个维度,不打虚构分数。
Compare mechanisms and constraints instead of presenting subjective impressions as a radar chart.比较机制和约束,而不是把主观印象包装成雷达图。
Showing all 8 dimensions. Engineering choices depend on the platform, workload, and team experience.显示全部 8 个维度。工程选择需要结合平台、工作负载与团队经验。
After the container grows, is that reference still valid?容器扩容后,那个引用还在吗?
fn main() {
let mut items = vec![10, 20, 30];
let first = &items[0];
// 扩容需要可变借用
items.reserve(items.capacity() + 1);
println!("{first}");
}first is used later; the immutable borrow of items conflicts with the mutable borrow required by reserve.first 后续仍要使用;对 items 的不可变借用与 reserve 所需的可变借用冲突。
#include <iostream>
#include <vector>
int main() {
std::vector<int> items{10, 20, 30};
const int& first = items[0];
items.reserve(items.capacity() + 1);
std::cout << first << '\n'; // 引用已失效
}reserve requests more than the current capacity and reallocates on success. Reading first afterwards is undefined behavior, not a reliable output.reserve 请求超过当前容量,成功后会重新分配;此时读取 first 是未定义行为,不是可靠的输出。
Reference invalidation in four steps.把引用失效,拆成四步。
C++ problem version · Illustrative memory layoutC++ 问题版本 · 内存布局示意First a container, then its elements.先有容器,再有元素。
items manages a buffer containing the elements. A and B in the diagram are illustrative addresses, not measurements.items 管理一块缓冲区,元素存放在其中。图中的 A、B 只是示意地址,不是真实测量。
API detail: Rust reserve(n) reserves space for n additional elements; C++ reserve(n) specifies a lower bound on capacity. Both examples request more than the current capacity, but they do not form an equal-work performance comparison.[21][25]API 细节:Rust reserve(n) 预留 n 个额外元素的空间;C++ reserve(n) 指定容量下界。本例都请求超过当前容量,但不是等工作量的性能对照。[21][25]
Not every growth operation reallocates; this example deliberately exceeds the current capacity. Rust also conservatively rejects some borrow patterns that are actually safe but cannot be proven safe by its current static rules.[04][21]这不是说每次扩容操作都会重新分配;示例特意请求超过当前容量。Rust 还会保守地拒绝部分实际上安全、但无法被当前静态规则证明安全的借用方式。[04][21]
There is no universal ranking of which language is faster.没有一条通用的“谁更快”排名。
Similar performance goals do not make every piece of code equally fast.相似的性能目标,
不等于每段代码一样快。
This indicates similar performance goals, not equal benchmark results.[09]这里只表示性能目标相近,
不表示基准测试结果相等。[09]
Neither requires a global tracing garbage collector, and both can express low-level work through higher-level abstractions. Rust checks ownership at compile time; C++ RAII ties resource release to object lifetimes.[01][05][09]两者都不要求全局追踪式垃圾回收器,也都能用高层抽象表达底层工作。Rust 的所有权检查发生在编译期,C++ 的 RAII 将资源释放绑定到对象生命周期。[01][05][09]
Bounds checks, dynamic dispatch, reference counting, allocation, and synchronization can still incur runtime costs. One Rust implementation beating one C++ implementation does not make the whole language faster, or vice versa. The following is a proposed comparison design, not completed benchmark results.[09][10]但边界检查、动态分派、引用计数、分配和同步仍可能有运行时成本。某段 Rust 比某段 C++ 快,不足以推出整门语言更快;反过来也一样。以下是建议的对照实验设计,而非已完成的跑分。[09][10]
Match the workload first先把工作量对齐
Use the same algorithms, data sizes, and error semantics. Avoid comparing data copying on one side with borrowing on the other.相同算法、数据规模与错误语义,避免一边复制数据、一边只借用。
Then match the environment再把环境对齐
Use optimized builds on the same hardware. Record compilers, optimization levels, CPU targets, and LTO settings.优化构建、相同硬件;记录编译器、优化级别、CPU 目标与 LTO 设置。
Measure your actual objectives测你的真实目标
Measure throughput, tail latency, peak memory, and artifact size. Record build times separately instead of mixing everything into one score.吞吐、尾延迟、峰值内存与产物体积;构建时间单独记录,不混成一个分数。
Explain differences through profiling用剖析解释差异
Repeat measurements and report variation. Inspect allocations, lock contention, and hot code instead of retaining only the fastest run.重复测量并报告波动;检查分配、锁竞争与热点代码,别只保留最快一次。
Rust: move some costs earlierRust:把部分成本提前
Clarifying ownership through compiler errors and API design can make the start more demanding. More lifetime problems surface before execution, but later debugging costs do not disappear.[02][04]在编译错误和 API 设计中澄清所有权,可能让起步更费脑;好处是更多生命周期问题在运行前暴露。并不意味着后续没有调试成本。[02][04]
Engineering judgment: the cost of learning borrowing rules depends on existing programming habits.工程判断:借用规则的学习成本,会受既有编程习惯影响。C++: maintain boundaries through ongoing disciplineC++:用持续治理守住边界
RAII and good interfaces reduce risks, but reference invalidation and data races still require guidelines, analysis, and testing. A familiar toolchain is itself a source of productivity.[05][19][20][21]RAII 和良好接口能减少风险,但引用失效和数据竞争仍要求规范、分析与测试共同把关。熟悉的工具链本身也是生产力。[05][19][20][21]
Engineering judgment: there is no learning-curve ranking that applies to every team.工程判断:没有适用于所有团队的“学习曲线高低排名”。Start with your scenario, not a side.别先站队,先选你的场景。
Select a project type to see a suggested direction, the reasoning, and conditions to verify before choosing. These are conditional engineering suggestions, not limits on language capability.点击一个项目类型,查看推荐方向、理由,以及选型前必须验证的条件。以下是有前提的工程建议,不是语言能力上限。
Evaluate Rust first优先评估 Rust
For protocol parsers, proxy services, or new infrastructure modules, make memory safety a default design constraint when dependencies and platforms meet requirements.协议解析、代理服务或基础设施新模块:在依赖与平台满足要求时,把内存安全作为默认设计约束。
Why为什么
These boundaries often handle external input. Rust's borrowing rules and cross-thread type constraints are useful, but choosing Rust does not eliminate security vulnerabilities.[02][03][04]这类边界经常接触外部输入。Rust 的借用规则和跨线程类型约束值得利用;不是“选了 Rust 就不会有安全漏洞”。[02][03][04]
What to verify first先验证什么
Check asynchronous runtimes, key libraries, training costs, throughput, and tail latency. Application logic, rate limiting, and protection against resource exhaustion still need design.先验证异步运行时与关键库、团队培训成本、吞吐及尾延迟。业务逻辑、限流和资源耗尽防护仍需设计。
Decision reminder: already have a mature C++ service with only small changes needed? Retain its core and pilot a clearly bounded module instead of rewriting just to change languages.决策提醒:已有成熟 C++ 服务且改动很小?先保留主体,在明确边界试点,不要为换语言而重写。
A third path: you do not have to rewrite everything.第三条路:不用把世界重写一遍。
With substantial existing C++ assets, finding stable boundaries for new modules may be more reasonable than replacing the whole codebase. This is a migration strategy, not a guarantee of benefits.已有大量 C++ 资产时,先为新模块找到稳定边界,可能比整库替换更合理。这是一种迁移策略,不是自动获益的保证。
Keep the proven core and apply new constraints at new boundaries.保留经过验证的核心,
让新边界获得新的约束。
A POSSIBLE MIGRATION SHAPE一种可行的迁移结构Existing engines and core libraries既有引擎与核心库
Retain vendor SDKs, performance-critical code, and validated system behavior.保留厂商 SDK、性能热点
以及已经验证的系统行为。
Ownership · Data representation · Error conversion · Threading contracts所有权 · 数据表示
错误转换 · 线程契约
New modules with clear boundaries边界清晰的新模块
Examples include parsing, validation, and independent service components. Begin with loosely coupled areas that permit rollback.例如解析、校验或独立服务组件。
先从低耦合、可回退的地方试点。
CXX generates bridges for supported types and signatures, but does not accept arbitrary C++ interfaces or automatically make old implementations safe. Cross-language exceptions, Result, and panic must follow the chosen bridge's rules.[13][14]CXX 可以为支持的类型与签名生成桥接,但不接受任意 C++ 接口,也不会让旧实现自动变安全。跨语言异常、Result 和 panic 的行为必须按所选桥接规则处理。[13][14]
Choose the boundary before counting rewritten lines先选边界,不先算重写行数
Prefer modules with few dependencies and testable behavior. Define inputs, outputs, and rollback plans.优先依赖少、行为可测试的模块;明确输入输出和回退方案。
Document and test the cross-language contract把跨语言契约写成文档与测试
Make allocation, release, cross-thread access, and error-return responsibilities verifiable.谁分配、谁释放、是否可跨线程、错误如何返回,都要可验证。
Let engineering outcomes determine expansion用工程结果决定是否扩大
Compare maintenance costs, failure risks, and end-to-end performance, rather than only the adoption percentage.比较维护成本、故障风险和端到端性能,而不只看采用比例。
Four claims that are easy to overstate.四个容易说过头的结论。
These qualifications determine whether the comparisons above hold.这些限定条件,决定了前面的比较是否真正成立。
“If Rust compiles, is it guaranteed to have no bugs?”“Rust 编译通过,就一定没有 bug?”
No. Memory safety is not application correctness. Safe Rust can still deadlock, suffer logical races, or leak memory. Incorrect unsafe abstractions, FFI, and underlying implementations can also break safety guarantees. Testing, audits, and resource management remain necessary.[04][06][22]不是。内存安全不等于业务正确。Safe Rust 仍可能死锁、出现逻辑竞态或泄漏内存;错误的 unsafe 抽象、FFI 和底层实现还可能破坏安全保证。测试、审计和资源治理仍然必要。[04][06][22]
“C++ has smart pointers, so are its guarantees the same as Rust's?”“C++ 有智能指针,所以和 Rust 的保证一样?”
No. Smart pointers primarily express and manage ownership. They do not automatically verify the lifetimes of arbitrary raw pointers, references, iterators, or views, or eliminate data races inside shared objects. Modern C++ can greatly reduce risk, but good practice differs from language-enforced guarantees.[05][20][21]不是。智能指针主要表达和管理所有权,不会自动验证任意裸指针、引用、迭代器或视图的生命周期;也不自动解决共享对象内部的数据竞争。现代 C++ 可以显著减少风险,但要区分优秀实践与语言强制的保证。[05][20][21]
“Does unsafe disable every Rust safety check?”“unsafe 就是关闭 Rust 的所有安全检查?”
No. unsafe permits certain operations the compiler cannot verify, such as dereferencing raw pointers or calling unsafe functions. It does not disable borrow checking. Confine such operations to small, auditable boundaries and satisfy their safety contracts.[04]不是。unsafe 允许进行某些编译器无法验证的操作,例如解引用裸指针、调用 unsafe 函数;它并不会关闭借用检查。正确做法是把特殊操作限制在可审计的小边界内,并满足其安全契约。[04]
“Rust needs no GC, so it never leaks; C++ must always be faster?”“Rust 不需要 GC,所以绝不泄漏;C++ 一定更快?”
Neither claim holds. Strong reference cycles can leak in Rust, and whether a language requires garbage collection does not determine an implementation's performance. Both can be efficient or slowed by poor implementation and configuration. Performance conclusions must specify workloads and test conditions.[01][09][22]两句话都不成立。Rust 的强引用循环可能泄漏;而语言是否需要垃圾回收器,也不足以推出某个实现的性能。两者都可以高效,也都可能因实现与配置失当而变慢。性能结论必须绑定具体负载和测试条件。[01][09][22]
Choose what fits your constraints, not a supposedly better language.选的不是“更好的语言”,
而是更适合你的约束。
My selection principles: for greenfield projects, check Rust's safety benefits and dependency availability; with deep C++ ecosystem dependencies, assess reuse first; for large existing systems, favor gradual changes that are verifiable and reversible.我的选型原则:绿地项目先核对 Rust 的安全收益与依赖可用性;深度依赖 C++ 生态时先看复用价值;已有大型系统,优先考虑可验证、可回退的渐进演进。
References and verification notes参考资料与核对说明25 PRIMARY SOURCES · 展开 +
Sources checked on September 22, 2026. Language mechanisms come from official documentation, primary project materials, and the C++ working draft. Selection and cost judgments are this article's analysis of those mechanisms. No cross-language performance benchmarks were performed, and no market-share statistics or invented quantitative scores are used. External documentation may change; pin toolchain and dependency versions for concrete projects.资料核对日期:2026 年 9 月 22 日。语言机制来自官方文档、项目原始资料与 C++ 工作草案。选型建议和成本判断为本文基于这些机制的分析;本文没有进行跨语言性能基准测试,没有引用市场份额或虚构量化评分。外部文档可能随版本更新,具体项目请锁定工具链与依赖版本。
- 01Rust Book · What Is Ownership? ↗
Ownership, move semantics, and resource release without reliance on a garbage collector.所有权、移动语义与资源释放;不依赖垃圾回收器。
- 02Rust Book · References and Borrowing ↗
Borrowing rules, reference validity, and compile-time conflict checks.借用规则、引用有效性与编译期冲突检查。
- 03Rust Book · Send and Sync ↗
Type constraints on cross-thread transfer and sharing.类型在跨线程转移和共享时的约束。
- 04Rust Book · Unsafe Rust ↗
The capabilities of unsafe, conservative static analysis, and safe abstractions.unsafe 的能力、静态分析的保守性与安全抽象。
- 05C++ Core Guidelines ↗
RAII, ownership, smart pointers, and safety practices in modern C++.现代 C++ 的 RAII、所有权、智能指针与安全实践。
- 06Rustonomicon · Data Races and Race Conditions ↗
The scope of data-race guarantees and the boundaries around deadlocks and logical races.数据竞争保障的范围,以及死锁和逻辑竞争的边界。
- 07The Cargo Book · Introduction ↗
Cargo's dependency management, build, and distribution responsibilities.Cargo 的依赖管理、构建与分发职责。
- 08The Cargo Book · cargo test ↗
A unified entry point for unit, integration, and documentation tests.单元测试、集成测试与文档测试的统一入口。
- 09Rust Book · Performance in Loops vs. Iterators ↗
The meaning of zero-cost abstractions; this article does not turn example benchmarks into a language ranking.零成本抽象的含义;文中未将示例基准扩展为语言排名。
- 10Rust Book · Generic Data Types ↗
Generic monomorphization: generating code for concrete types at compile time.泛型的单态化:在编译期生成具体类型对应的代码。
- 11CMake · Official Tutorial ↗
CMake workflows for project configuration, building, and testing.CMake 的项目配置、构建与测试工作流。
- 12Microsoft Learn · vcpkg Overview ↗
C/C++ dependency management and build-system integration.C/C++ 依赖管理与构建系统集成。
- 13CXX · Rust–C++ Interop ↗
Generating cross-language bridges for supported types and interfaces.通过受支持的类型和接口生成跨语言桥接。
- 14CXX · Result<T> ↗
Specific rules for cross-language error conversion, C++ exceptions, and Rust panics.跨语言错误转换、C++ 异常与 Rust panic 的具体规则。
- 15Epic Games · Programming with C++ ↗
Unreal Engine's C++ framework and development workflow.Unreal Engine 的 C++ 框架与开发工作流。
- 16Qt · Introduction to Qt ↗
C++, QML, platform support, and tooling in Qt.Qt 中的 C++、QML、平台支持和工具链。
- 17NVIDIA · CUDA Programming Guide ↗
CUDA C++'s official programming model, compilers, and platform capabilities.CUDA C++ 的官方编程模型、编译器与平台能力。
- 18The rustc Book · Platform Support ↗
Target platform support tiers; being compilable is not equivalent to full product support.目标平台的分级支持;不能把可编译等同于完整产品支持。
- 19Clang · AddressSanitizer ↗
Runtime detection of memory errors such as out-of-bounds access and use after free.运行时检测越界访问、释放后使用等内存错误。
- 20Clang · ThreadSanitizer ↗
Runtime data-race detection, which cannot replace a complete correctness proof.运行时检测数据竞争;不能替代完整正确性证明。
- 21C++ Working Draft · vector.capacity ↗
Conditions for reserve reallocation and rules for invalidating references, pointers, and iterators.reserve 的重新分配条件以及引用、指针和迭代器失效规则。
- 22Rust Book · Reference Cycles Can Leak Memory ↗
Safe Rust can still leak memory through mechanisms such as strong reference cycles.Safe Rust 仍可能因强引用循环等原因泄漏内存。
- 23Rust Book · Recoverable Errors with Result ↗
Expressing and propagating recoverable errors with Result.通过 Result 表达和传播可恢复错误。
- 24C++ Working Draft · General Utilities ↗
Modern C++ utility types including optional, variant, and expected.包括 optional、variant、expected 等现代 C++ 工具类型。
- 25Rust Standard Library · Vec::reserve ↗
Rust reserve's additional parameter counts extra elements, unlike the lower bound on capacity specified by C++ reserve.reserve 的 additional 参数表示额外元素数量,与 C++ reserve 的容量下界不同。