C++ 高级特性

C++ 高级特性概述

C++ 的高级特性包括模板元编程、智能指针、移动语义、多线程、Lambda 表达式等,这些特性有助于提升代码的灵活性、性能和可维护性。

模板元编程

模板元编程(TMP)利用编译期计算优化运行时性能,常用于生成高效代码或实现编译时逻辑判断。其核心思想是通过模板的递归实例化和特化,将运行时逻辑转移到编译期完成,从而提高运行时效率或实现代码生成自动化

通过递归的模板实例化和特化,可以实现编译期的循环与条件判断。

例如,计算阶乘的模板元编程实现:

template <int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static const int value = 1;
};

// 使用:Factorial<5>::value 在编译期计算为 120

编译器会展开递归直到基例(Factorial<0>),最终结果在编译期确定。

智能指针

智能指针(如 std::shared_ptrstd::unique_ptr)自动管理内存,避免内存泄漏。

#include <memory>
std::unique_ptr<int> ptr = std::make_unique<int>(42); // 独占所有权
std::shared_ptr<int> sharedPtr = std::make_shared<int>(100); // 共享所有权

SFINAE(Substitution Failure Is Not An Error)
通过模板匹配失败来约束模板的适用性。例如,检测类型是否具有某个成员函数:

移动语义

移动语义(Move Semantics)通过 std::move 转移资源所有权,减少拷贝开销。

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = std::move(v1); // v1 的资源转移至 v2

多线程与并发

C++11 引入的 <thread><future> 支持多线程编程。

#include <thread>
#include <iostream>

void task() {
    std::cout << "Running in thread" << std::endl;
}

int main() {
    std::thread t(task);
    t.join();
    return 0;
}

Lambda 表达式

Lambda 表达式提供匿名函数的便捷语法,常用于算法回调。

std::vector<int> nums = {1, 2, 3};
std::sort(nums.begin(), nums.end(), [](int a, int b) {
    return a > b; // 降序排序
});

类型推导与 auto

auto 关键字简化类型声明,尤其在模板和迭代器中。

auto x = 10; // x 推导为 int
std::vector<std::string> names = {"Alice", "Bob"};
for (const auto& name : names) {
    std::cout << name << std::endl;
}

右值引用与完美转发

右值引用(T&&)支持高效资源转移,完美转发(std::forward)保留参数类型。

template <typename T>
void wrapper(T&& arg) {
    process(std::forward<T>(arg)); // 保持 arg 的左右值属性
}

这些特性是 C++ 现代编程的核心,合理使用可显著提升代码质量与性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值