返回博客列表
C++

现代C++最佳实践指南

了解C++11/17/20的新特性,掌握现代C++编程的最佳实践

2025-01-10
15 分钟 阅读

现代C++最佳实践指南

引言

现代C++(C++11/17/20)引入了许多强大特性,让我们能够编写更安全、更高效的代码。本文将介绍这些新特性以及如何在实际项目中应用它们。

智能指针

unique_ptr

unique_ptr 是独占所有权的智能指针,当它离开作用域时自动删除对象。

#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(42);

// 转移所有权
std::unique_ptr<int> ptr2 = std::move(ptr);

shared_ptr

shared_ptr 是共享所有权的智能指针,使用引用计数管理对象生命周期。

#include <memory>

auto ptr = std::make_shared<int>(42);
auto ptr2 = ptr;  // 共享所有权

weak_ptr

weak_ptr 用于观察 shared_ptr,不增加引用计数,避免循环引用。

std::weak_ptr<int> weak = ptr;
if (auto shared = weak.lock()) {
    // 使用shared
}

Lambda表达式

auto func = [](int x, int y) { return x + y; };

// 捕获列表
int value = 10;
auto lambda = [value](int x) { return x + value; };

auto关键字

auto x = 42;  // int
auto y = 3.14;  // double
auto z = std::make_unique<int>(42);  // std::unique_ptr<int>

范围for循环

std::vector<int> vec = {1, 2, 3, 4, 5};

for (const auto& item : vec) {
    std::cout << item << " ";
}

右值引用与移动语义

std::string str1 = "Hello";
std::string str2 = std::move(str1);  // 移动而非拷贝

constexpr

constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

constexpr int result = factorial(5);  // 编译期计算

总结

现代C++提供了强大的特性:

  1. 智能指针 - 自动内存管理
  2. Lambda表达式 - 简洁的匿名函数
  3. auto关键字 - 类型推导
  4. 范围for - 简化的遍历
  5. 移动语义 - 性能优化
  6. 线程支持 - 并发编程
  7. filesystem - 文件系统操作
  8. 结构化绑定 - 清晰的代码

掌握这些最佳实践将帮助你写出更好的C++代码。

相关文章