当前位置: 首页 > article >正文

深入浅出C++11新特性详解

一、自动类型推导

1.1 auto关键字

// 传统迭代器声明
std::vector<int>::iterator it = vec.begin();
// C++11 auto推导
auto auto_it = vec.begin(); // 自动推导为vector<int>::iterator

1.2 decltype类型推导

int x = 5;
decltype(x) y = 10;  // y的类型与x相同(int)

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
    return t + u;
}

 

二、现代化循环

2.1 基于范围的for循环

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

// 传统遍历方式
for(std::vector<int>::iterator it = nums.begin(); 
    it != nums.end(); ++it) {
    std::cout << *it << " ";
}

// C++11范围遍历
for(auto& num : nums) {
    std::cout << num << " ";
}

三、智能指针(内存管理革命)

3.1 unique_ptr

std::unique_ptr<int> p1(new int(5));
// std::unique_ptr<int> p2 = p1; // 错误:禁止拷贝

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

3.2 shared_ptr与weak_ptr

class Node {
public:
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev; // 防止循环引用
};

auto node1 = std::make_shared<Node>();
auto node2 = std::make_shared<Node>();
node1->next = node2;
node2->prev = node1;

四、移动语义与完美转发

4.1 右值引用

class StringWrapper {
public:
    // 移动构造函数
    StringWrapper(StringWrapper&& other) noexcept 
        : data_(other.data_), size_(other.size_) {
        other.data_ = nullptr;  // 转移资源所有权
    }

private:
    char* data_;
    size_t size_;
};

4.2 完美转发

template<typename T>
void wrapper(T&& arg) {
    worker(std::forward<T>(arg));  // 保持参数的值类别
}

五、Lambda表达式(函数式编程)

std::vector<int> numbers{3,1,4,1,5};

// 使用lambda进行排序
std::sort(numbers.begin(), numbers.end(), 
          [](int a, int b) { return a > b; });

// 捕获列表示例
int base = 10;
std::for_each(numbers.begin(), numbers.end(), 
             [base](int n) { std::cout << n + base << " "; });

六、编译期计算

6.1 constexpr

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

int main() {
    constexpr int fact5 = factorial(5);  // 编译期计算120
    int arr[fact5];  // 合法声明数组
}

七、模板增强

7.1 变长参数模板 

template<typename... Args>
void printAll(Args... args) {
    // 使用折叠表达式展开参数包
    (std::cout << ... << args) << "\n";
}

printAll(1, "apple", 3.14);  // 输出:1apple3.14

八、并发支持

8.1 原子操作

#include <atomic>
std::atomic<int> counter(0);

void increment() {
    for(int i=0; i<100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

8.2 线程库

#include <thread>
#include <future>

auto future = std::async([](){ return 42; }); // 异步任务
std::cout << future.get();  // 输出42

std::thread t([](){
    std::cout << "Hello from thread!\n";
});
t.join();

九、其他重要特性

9.1 强类型枚举

enum class Color : uint8_t { Red = 0xFF, Green = 0x00FF }; // 指定底层类型

Color c = Color::Red;
// int i = c; // 错误,禁止隐式转换

9.2 委托构造函数

class Circle {
public:
    Circle() : Circle(1.0) {}  // 委托构造函数
    explicit Circle(double r) : radius(r) {}
private:
    double radius;
};

专栏特色

  1. 每个特性配套可编译的完整代码示例
  2. 对比传统C++实现与新特性的优劣
  3. 性能优化点特别标注(如移动语义对STL的影响)

http://www.kler.cn/a/561739.html

相关文章:

  • 2.25DFS和BFS刷题
  • Windows cmd 的没有下划线怎么办
  • 基于 SpringBoot Vue 的生鲜商城系统设计和实现(源码+文档+部署讲解)
  • Spring MVC 的执行流程解析:从用户请求到响应返回
  • github 部署前端静态网页(react vite)
  • 理解 SQL Server 锁粒度:优化并发性能与数据一致性
  • 微信小程序源码逆向 MacOS
  • 容器技术对传统配置管理工具痛点的补充
  • Deepseek 实战全攻略,领航科技应用的深度探索之旅
  • MFC—加法器
  • spark 虚拟机基本命令(2)
  • 从 Linux 服务器到前端到网关到后端业务逻辑的分析
  • 深度剖析Seata源码:解锁分布式事务处理的核心逻辑
  • 如何安全使用短脉冲红外激光器防止激光辐射伤害的方法
  • jspssm526springboot 教师人事档案管理系统
  • 芯旺微KF32A156芯片CANFD过滤配置
  • JavaScript的BOM编程
  • 【NLP算法面经】腾讯、头条算法岗详细面经(★附面题整理★)
  • MFC案例:利用双缓冲技术绘制顶点可移动三角形
  • 【新算法】基于Transformer-LSTM-Adaboost的多输入单输出回归预测模型【MATLAB】