C++11 引入了许多新的特性和改进,使得 C++ 语言在性能和易用性上都有了显著的提升。以下是一些 C++11 在实际世界中的应用示例:
1. 使用智能指针管理资源
在 C++11 中,引入了智能指针(如 std::unique_ptr
和 std::shared_ptr
),这大大简化了资源管理。
- 示例代码:
#include <iostream> #include <memory> int main() { std::unique_ptr<int> ptr(new int(10)); std::cout << "Value: " << *ptr << std::endl; return 0; }
2. 使用 Lambda 表达式
Lambda 表达式允许你以更简洁的方式定义匿名函数。
- 示例代码:
auto lambda = []() { std::cout << "Hello, World!" << std::endl; }; lambda();
3. 使用线程安全容器
C++11 提供了线程安全的容器,如 std::mutex
和 std::lock_guard
。
- 示例代码:
#include <iostream> #include <mutex> std::mutex mtx; void printHello() { std::lock_guard<std::mutex> lock(mtx); std::cout << "Hello, World!" << std::endl; } int main() { std::thread t1(printHello); std::thread t2(printHello); t1.join(); t2.join(); return 0; }
4. 使用范围for循环
C++11 支持使用范围for循环来遍历容器。
- 示例代码:
#include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; for (int i : vec) { std::cout << i << std::endl; } return 0; }
更多关于 C++11 的内容,请参考本站 C++11 教程。
图片展示
C++11