C++11 新特性详解:革命性的现代化更新
·
C++11 新特性详解:革命性的现代化更新
C++11(原称C++0x)是C++编程语言的一次重大更新,被广泛认为是自1998年C++标准化以来最重要的版本。相较于C++03,C++11引入了大量革命性特性,使C++成为一门更现代化、更安全、更高效的编程语言。
一、语言核心特性
1. 自动类型推导(auto)
auto i = 42; // int
auto d = 3.14; // double
auto v = std::vector<int>(); // std::vector<int>
2. 基于范围的for循环
std::vector<int> v = {1, 2, 3};
for (auto& num : v) { // 遍历容器更简洁
num *= 2;
}
3. 右值引用和移动语义
class String {
char* data;
public:
// 移动构造函数
String(String&& other) noexcept
: data(other.data) {
other.data = nullptr;
}
// 移动赋值运算符
String& operator=(String&& other) noexcept {
delete[] data;
data = other.data;
other.data = nullptr;
return *this;
}
};
4. Lambda表达式
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end(), [](int a, int b) {
return a > b; // 降序排序
});
5. 强类型枚举(enum class)
enum class Color { Red, Green, Blue }; // 不会污染外层命名空间
Color c = Color::Red;
// int i = Color::Red; // 错误,不能隐式转换
6. 空指针常量(nullptr)
void foo(int* p);
void foo(int i);
foo(nullptr); // 明确调用foo(int*)
7. 静态断言(static_assert)
static_assert(sizeof(void*) == 8, "Requires 64-bit platform");
8. 委托构造函数
class Foo {
public:
Foo() : Foo(0) {} // 委托给另一个构造函数
Foo(int i) : x(i) {}
private:
int x;
};
9. 继承构造函数
class Base {
public:
Base(int);
};
class Derived : public Base {
public:
using Base::Base; // 继承基类构造函数
};
10. 变长模板参数
template<typename... Args>
void print(Args... args) {
(std::cout << ... << args) << '\n'; // C++17折叠表达式
}
二、内存管理改进
1. 智能指针
#include <memory>
// 独占所有权
std::unique_ptr<int> p1(new int(42));
// 共享所有权
std::shared_ptr<int> p2 = std::make_shared<int>(42);
// 弱引用
std::weak_ptr<int> p3 = p2;
2. 对齐支持
alignas(16) float array[4]; // 16字节对齐
auto align = alignof(int); // 获取对齐要求
三、标准库增强
1. 线程支持
#include <thread>
#include <mutex>
std::mutex m;
void foo() {
std::lock_guard<std::mutex> lock(m);
// 临界区
}
std::thread t(foo);
t.join();
2. 时间库
#include <chrono>
auto start = std::chrono::steady_clock::now();
// 执行操作...
auto end = std::chrono::steady_clock::now();
auto elapsed = end - start;
3. 正则表达式
#include <regex>
std::regex pattern(R"(\d{3}-\d{4})");
std::string text = "123-4567";
if (std::regex_match(text, pattern)) {
// 匹配成功
}
4. 随机数库
#include <random>
std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<> dis(1, 6);
int dice = dis(gen); // 1到6的随机数
5. 无序容器
#include <unordered_map>
std::unordered_map<std::string, int> word_counts;
word_counts["hello"] = 1;
6. 元组
#include <tuple>
auto t = std::make_tuple(1, "hello", 3.14);
int i = std::get<0>(t); // 获取第一个元素
7. 数组容器
#include <array>
std::array<int, 3> a = {1, 2, 3};
四、其他重要特性
1. 原始字符串字面量
const char* path = R"(C:\Program Files\App)"; // 不需要转义反斜杠
const char* html = R"(
<html>
<body>Hello</body>
</html>
)";
2. 用户定义字面量
long double operator"" _deg(long double deg) {
return deg * 3.1415926535897932385L / 180;
}
auto angle = 90.0_deg; // 转换为弧度
3. 属性语法
[[noreturn]] void fatal_error() {
throw std::runtime_error("Error");
}
4. 默认和删除函数
class NonCopyable {
public:
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
};
五、总结
C++11 的主要改进包括:
- 自动类型推导:
auto和decltype简化复杂类型声明 - 智能指针:
unique_ptr/shared_ptr/weak_ptr提供更安全的内存管理 - 移动语义:显著提升性能,特别是容器和大型对象
- 多线程支持:标准化的线程、互斥量和条件变量
- Lambda表达式:方便的函数式编程支持
- 标准库扩展:正则表达式、随机数、时间库等
- 初始化改进:统一初始化语法和初始化列表
- 模板增强:变长模板参数和模板别名
C++11 的这些变化使C++成为一门更现代化、更安全、更高效的编程语言,为后续的C++14、C++17和C++20奠定了基础。
更多推荐
所有评论(0)