代码能跑不代表没有改进空间。以下是切换到 C++11 的 9 个理由。
性能提升 1. Move 语义 避免不必要的深拷贝。当源对象是临时对象时,直接"偷走"资源而不是复制:
// C++03:深拷贝,浪费 std::string s = get_temp_string(); // C++11:move,零拷贝 std::string s = std::move(get_temp_string()); STL 容器(string、vector 等)已内置支持,存储到容器时自动优化。
2. 模板元编程优化 通过 type_traits(如 is_floating_point)和 enable_if,为特定类型定制模板实现。
3. 哈希表 标准库新增 unordered_map、unordered_set 等,基于哈希表实现,查找 O(1),比 map(红黑树 O(log n))更快。
开发效率 4. auto 关键字 自动类型推导,减少冗余代码:
// C++03 std::vector<std::vector<MyType>>::const_iterator it = v.begin(); // C++11 auto it = v.cbegin(); 5. Lambda 表达式 定义匿名函数,配合 STL 算法使用非常方便:
bool is_safe() { return std::all_of(tanks.begin(), tanks.end(), [this](const Tank& t) { return t.fuel_level() > min_level; }); } 6. 智能指针 unique_ptr 和 shared_ptr 替代原始指针,自动管理内存,杜绝泄漏:
auto p = std::make_unique<MyClass>(); // 离开作用域自动释放 7. std::function 函数作为一等对象,可以包装函数指针、lambda、仿函数等任何可调用对象:
std::function<int(int, int)> op = [](int a, int b) { return a + b; }; 8. 更清晰的表达 override、final、nullptr、enum class 等让代码意图更明确,减少 bug。
...