专业编程基础技术教程

网站首页 > 基础教程 正文

C++开发:C++11 和 C++17 编程新特性介绍

ccvgpt 2024-11-03 13:21:53 基础教程 8 ℃

C++11 和 C++17 是 C++ 语言的两个重要版本,它们引入了许多新的特性和改进。以下是对这两个版本主要特性的介绍:

C++11 特性

C++11 是一个重大更新,添加了许多新特性,使得 C++ 更加现代化和易用。以下是一些关键特性:

C++开发:C++11 和 C++17 编程新特性介绍

自动类型推导 (auto):

auto i = 10; // 编译器会自动推导出 i 的类型为 int

范围 for 循环:

std::vector<int> vec = {1, 2, 3, 4}; 
for (auto& v : vec) {
  std::cout << v << " "; 
}

Lambda 表达式:

auto add = [](int a, int b) { return a + b; }; 
std::cout << add(2, 3); // 输出 5

智能指针:

std::unique_ptr<int> ptr = std::make_unique<int>(10); 
std::shared_ptr<int> sptr = std::make_shared<int>(20);

右值引用和移动语义:

std::vector<int> vec1 = {1, 2, 3}; 
std::vector<int> vec2 = std::move(vec1); // vec1 的资源被移动到 vec2

nullptr 关键字:

int* p = nullptr; // 用于替代 NULL

线程库:

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

constexpr 关键字:

constexpr int square(int x) { return x * x; } 
int arr[square(3)]; // arr 的大小为 9

静态断言 (static_assert):

static_assert(sizeof(int) == 4, "Integers must be 4 bytes");

新标准库容器:

  • std::array
  • std::unordered_map
  • std::unordered_set

C++17 特性

C++17 引入了一些增量改进和新特性,进一步增强了 C++ 的功能和易用性。以下是一些主要特性:

结构化绑定:

std::tuple<int, double, std::string> t(1, 2.3, "hello"); 
auto [i, d, s] = t;

if 和 switch 的初始化:

if (int x = f(); x > 0) { 
  // 使用 x 
} 
switch (int y = g(); y) { 
  case 1: 
  	// 使用 y 
  break;
}

std::optional:

std::optional<int> opt = 42;
if (opt) { 
  std::cout << *opt; // 输出 42
}

std::variant 和 std::visit:

std::variant<int, float> v = 42; 
std::visit([](auto&& arg) { std::cout << arg; }, v); // 输出 42

std::any:

std::any a = 1; 
a = std::string("hello"); 
std::cout << std::any_cast<std::string>(a); // 输出 hello

折叠表达式:

template<typename... Args> auto sum(Args... args) { 
  return (args + ...); // 折叠表达式 
}

内联变量:

inline int x = 42;

std::filesystem 库:

std::filesystem::path p = "/path/to/file";
std::cout << std::filesystem::exists(p);

constexpr 的改进:

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

std::string_view:

std::string_view sv = "Hello, world";
std::cout << sv.substr(0, 5); // 输出 Hello

总结

C++11 和 C++17 都引入了许多新特性,使得 C++ 变得更强大和灵活。C++11 带来了大量的基础性改进和新特性,而 C++17 则是在此基础上进行了一些增量改进和优化。了解和使用这些新特性,可以帮助开发者编写更高效和现代化的 C++ 代码。

Tags:

最近发表
标签列表