C++中常用新特性

C++近年来加入了很多新特性,这些特性大大增强了语言的功能性、可读性和效率。以下是开发中一些常用的C++新特性(从C++11到C++20),简单总结,欢迎补充:

1. C++11

  • 自动类型推导 (auto):可以自动推导变量类型,减少代码冗余。
auto x = 42;  // 自动推导为 int
  • 范围-based for 循环:简化了对容器的遍历。
for (auto& elem : container) {    // 处理elem}
  • 智能指针 (std::unique_ptrstd::shared_ptr):用于自动管理内存,避免内存泄漏。
std::unique_ptr p = std::make_unique(10);
  • Lambda 表达式:允许定义匿名函数,减少了代码冗余。
auto lambda = [](int x) { return x * 2; };
  • 并发 (std::threadstd::mutex):增加了线程支持。
std::thread t([]() { /* 做一些工作 */ });t.join();
  • 右值引用和移动语义:引入了&&std::move,优化了资源管理和性能。
void func(std::vector&& vec) {    // 处理移动的资源}

2. C++14

  • 自动推导返回类型 (auto 返回类型):函数返回值类型可以使用auto推导。
auto func() { return 42; }
  • lambda 捕获 by move:允许lambda按值捕获并移动对象。
auto lambda = [x = std::move(my_object)]() { /* 使用x */ };
  • std::make_unique:简化了unique_ptr的创建。
auto p = std::make_unique(10);

3. C++17

  • 结构化绑定声明:可以解构元组、pair等。
auto [x, y] = std::make_pair(1, 2);
  • std::optional:表示一个可能为空的值。
std::optional opt = 42;
  • std::filesystem:标准库增加了对文件系统的支持。
namespace fs = std::filesystem;for (const auto& entry : fs::directory_iterator("/path/to/dir")) {    std::cout << entry.path() << std::endl;}
  • std::string_view:提供了对字符串的轻量级非拥有视图。
std::string_view str_view = "Hello, world!";

4. C++20

  • 概念(Concepts):提供了类型约束,增强了模板的可读性和可调试性。
template concept Incrementable = requires(T x) { ++x; };template void increment(T& x) { ++x; }
  • 范围库(Ranges):简化了对容器的操作,提供了管道式操作。
#include auto result = data | std::views::transform([](int x) { return x * 2; });
  • 协程(Coroutines):用于简化异步编程和生成器。
#include std::future get_data() {    co_return 42;}
  • 三向比较(Spaceship Operator <=> :简化了比较操作符的编写。
struct MyType {    int x, y;    auto operator<=>(const MyType&) const = default;};
  • std::span:提供对数组或容器的轻量级视图。
std::span span(arr, size);
  • consteval 和 constinit:分别用于在编译时求值和初始化常量表达式。
consteval int square(int x) { return x * x; }

这些新特性让C++变得更现代、简洁且高效。你有兴趣深入某一个特性或如何在项目中使用这些特性吗?

声明:本内容为作者独立观点,不代表电子星球立场。未经允许不得转载。授权事宜与稿件投诉,请联系:editor@netbroad.com
觉得内容不错的朋友,别忘了一键三连哦!
赞 2
收藏 2
关注 37
成为作者 赚取收益
全部留言
0/200
成为第一个和作者交流的人吧